Chartjs-Updating chart.js in ractive

1👍

If you are working with 3rd party plugins I would recommend to use Ractive’s decorators.
This post on ractivejs-and-jquery-plugins shows you a starting point how to implement a decorator based on a fileupload control.

In your case I would recommend to build a decorator with the data as parameter and do not forget to implement the UPDATE function (where in your case you gonna call the update method with the new data for your chart)

0👍

As I could not figure out how to write my own decorator for Chart.js I thought I post the solution that worked for me. I do not think it’s best practice and for sure decorators would be a better way (therefore I do not mark this solution as correct answer), but it works:

const Stats = '<canvas id="myChart" width="400" height="400"></canvas>'
new Ractive ({
    el: '#stats',
    template: Stats,
    magic: true,
    modifyArrays: true,
    data: {docs}, // <= some JSON Data
    computed: {
        Data1() {
            let tempList = this.get('docs');
            // rearrange & filter Data 
            return tempList ;
        },
        Data2() {
            let tempList2 = this.get('docs');
            // rearrange & filter Data 
            return tempList2 ;
        },
        Data3() {
            let tempList3 = this.get('docs');
            // rearrange & filter Data 
            return tempList3 ;
        },
        }

    },
    onrender: function () {
        let DataSet1 = this.get('Data1');
        let DataSet2 = this.get('Data2');
        let DataSet3 = this.get('Data3');
        let ctx = document.getElementById("myChart");
        myChart = new Chart(ctx, { 
            type: 'doughnut',
            data: {
                labels: ["Data 1", "Data 1", "Data 3"],
                datasets: [{
                    label: 'All my Data',
                    data: [DataSet1.length, DataSet2.length, DataSet3.length]
                }]
            }
        });

    },
    onchange: function () { 
        let changedData1 = this.get('Data1');
        let changedData2 = this.get('Data2');
        let changedData3 = this.get('Data3');
        myChart.data.datasets[0].data[0] = changedData1.length;
        myChart.data.datasets[0].data[1] = changedData2.length;
        myChart.data.datasets[0].data[2] = changedData3.length;
        myChart.update();
        }
    }
}); 

Leave a comment