Skip to content

Instantly share code, notes, and snippets.

@jmhdez
Last active February 11, 2019 15:32
Show Gist options
  • Save jmhdez/4987b053e817d65d7c68 to your computer and use it in GitHub Desktop.
Save jmhdez/4987b053e817d65d7c68 to your computer and use it in GitHub Desktop.
Custom bindings to use Chart.js with Knockout.js
/*global ko, Chart */
(function(ko, Chart) {
ko.bindingHandlers.chartType = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
if (!allBindings.has('chartData')) {
throw Error('chartType must be used in conjunction with chartData and (optionally) chartOptions');
}
},
update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var ctx = element.getContext('2d'),
type = ko.unwrap(valueAccessor()),
data = ko.unwrap(allBindings.get('chartData')),
options = ko.unwrap(allBindings.get('chartOptions')) || {};
if (this.chart) {
this.chart.destroy();
delete this.chart;
}
this.chart = new Chart(ctx)[type](data, options);
}
};
ko.bindingHandlers.chartData = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
if (!allBindings.has('chartType')) {
throw Error('chartData must be used in conjunction with chartType and (optionally) chartOptions');
}
}
};
ko.bindingHandlers.chartOptions = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
if (!allBindings.has('chartData') || !allBindings.has('chartType')) {
throw Error('chartOptions must be used in conjunction with chartType and chartData');
}
}
};
})(ko, Chart);
@disharide
Copy link

Any option of using the same without defining the colours inside the datasets? I am intending to fetch data from back end services. So Defining colours at that level is a bit tricky because I won't have any idea about the dataset's size.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment