score:0
Accepted answer
The main thing i can see is that you pass the chart data which is not in the format that chartjs expects, so it should be an array of objects which have the properties value
label
and color
but you are passing it something different. so a quick fix for that would be to construct an array as described
// Model
var Transaction = Backbone.Model.extend({
defaults: {
amount: 0,
transactionDate: "",
transactionType: "debit",
category: "miscellaneous",
description: ""
},
categories: [
"salary",
"rent",
"miscellaneous"
],
transactionTypes: [
"credit",
"debit"
],
initialize: function() {
this.set({
transactionDate: this.attributes.transactionDate || Date.now()
}, {
validate: true
});
},
validate: function(attrs, options) {
if (attrs['transactionType'] !== undefined && !_.contains(this.transactionTypes, attrs['transactionType'].toLowerCase())) {
return 'Invalid type: ' + attrs['transactionType'];
} else if (attrs['category'] !== undefined && !_.contains(this.categories, attrs['category'].toLowerCase())) {
return 'Invalid category: ' + attrs['category'];
} else if (attrs['transactionDate'] !== undefined && _.isNaN(parseInt(attrs['transactionDate'])) || attrs['transactionDate'] < 0) {
return 'Invalid date: ' + attrs['transactionDate'];
} else if (attrs['amount'] !== undefined && _.isNaN(parseInt(attrs['amount'])) || attrs['amount'] < 0) {
return 'Invalid amount: ' + attrs['amount'];
}
return null;
}
});
var Transactions = Backbone.Collection.extend({
// stuff and thangs
model: Transaction,
latestFive: function(toJSON) {
this.sortByDate(-1); // sort latest first
if (!toJSON) {
return _.first(this.models, 5);
} else {
var models = _.first(this.models, 5),
idx = -1,
json = [],
model;
while (model = models[++idx]) {
json.push(model.attributes);
}
return json;
}
},
sortByDate: function(dir) {
dir = dir || -1;
this.comparator = function(transaction) {
return dir * transaction.get("transactionDate");
};
this.sort();
},
sortByAmount: function(dir) {
dir = dir || -1;
this.comparator = function(transaction) {
return dir * transaction.get("amount");
};
this.sort();
}
});
var ChartView = Backbone.View.extend({
el: ".home-page",
template: Handlebars.compile($("#chart-template").html()),
chart: null,
initialize: function() {
this.listenTo(this.collection, "add", this.render);
this.listenTo(this.collection, "change", this.render);
this.$(".chart-view-div").html(this.template());
this.chart = new Chart(this.$("#expense-chart")[0].getContext("2d"));
this.render();
},
render: function() {
var self = this;
var data = this.chartData();
this.chart.Doughnut(data, {
responsive: true,
animateScale: true
});
},
chartData: function() {
var collection = this.collection.latestFive(true);
var data = [];;
var getData = function(color, highlight, labels, vals, collection) {
var object = {
color: color,
highlight: highlight,
chartData: [{
value: "",
label: ""
}]
};
for (var i = 0; i < labels.length; i++) {
object.chartData.push(0);
}
for (var j = 0; j < vals.length; j++) {
object.chartData.push(0);
}
for (var i = 0; i < collection.length; i++) {
var item = collection[i];
var label = labels.indexOf(item.category);
var val = vals.indexOf(item.amount);
object.chartData[{
value: val,
label: label
}] ++;
}
return object;
};
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
for (var i = 0; i < collection.length; i++) {
var object = collection[i];
var color = getRandomColor();
var highlight = getRandomColor();
data.push({
value: object.amount,
color: color,
label: object.category
});
}
return data;
}
});
var collection = new Transactions([{
amount: 12,
transactionDate: 1417442176000,
transactionType: "debit",
category: "miscellaneous",
description: ""
}, {
amount: 13,
transactionDate: 1417442176000,
transactionType: "credit",
category: "salary",
description: ""
}]);
var view = new ChartView({
collection: collection
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone.js"></script>
<script src="http://www.chartjs.org/assets/Chart.min.js"></script>
<script id="chart-template" type="text/x-handlebars-template">
<canvas id="expense-chart"></canvas>
</script>
<div class="home-page">
<div class="chart-view-div"></div>
</div>
Source: stackoverflow.com
Related Query
- Doughnut Chart not displaying data with Chart Js and Backbone js
- Chart.js: bar chart first bar and last bar not displaying in full
- ChartJS (React) Line Chart - How to show single tooltip with data and labels from 3 (multiple) dataset?
- Chart not displaying from JSON data
- Chart JS not showing On hover with small data
- How to get chart from data points (arrays) with inconsistent time intervals and chart.js?
- Vue Chart.js Doughnut Chart with rounded and spaced arcs (vue3-chart-v2)
- Doughnut chart updates with twice the data
- How to reuse a Chartjs Chart component in with different Data and get past the **Canvas is already in use** error?
- Chart not rendering with pug/jade and nodejs
- Javascript window.onload not displaying charts with Chart.js and Flask
- Chart with Time axis only displaying first grid line and tick label (unitStepSize)
- Chart.js not rendering chart with data from mySQL database
- Doughnut chart from Chart.js, custom legend and call of original handler not works as expected
- chart js download to png with canvas.toDataURL() not working in IE and firefox
- Charts JS: Doughnut chart and hiding tooltip for specific data index within each dataset
- Resetting transform: rotate() by removing and appending canvas not showing data after appending and redrawing chart
- Chart JS not working with Dynamic Data
- Chart.js combined line and bar chart with differing data points
- X and Y axis labels not displaying on line chart (Chart.js)
- Data not displaying properly in Chart.js line chart
- Displaying Chart with data retrieved from Entity Framework in Controller
- Chart Piechart in only show percentage on hover but it shows data and label with percentage both i just want to show percentage only percentage
- Chart.js bar chart with time on X axis and category on Y axis is not rendered
- ng2-charts doughnut chart with different data per series
- how to write labels along with data on top and bottom of each stack in bar chart
- ChartJS doughnut chart not displaying colours
- How write the labels of the data inside a Doughnut Chart made with Chart.js?
- Why is the data from my API not displaying on my chart.js chart in React?
- donut chart not rendering with csv data chart.js
More Query from same tag
- "Process is not defined" with react-chartjs-2 CDN
- ChartJs in ionic Framework
- Chartjs How to render a custom horizon line under X-Axis
- How to insert php in data chart.js
- save my chart.js output to an image
- chart.js show time in series
- get JSON data from function to give value to Chart JS
- How to install Chart.js without a library?
- Unable to change y-axis value dynamically based on data for Stacked bar chart in reactjs
- How to get item what been clicked on Chart (primeNg chart + angular application)
- implementing horizontal bar chart
- Get access to the chart.js component instance in React
- Chartjs with multiple y axes and different scales
- Change color on labels in chart.js
- How can I remove the white border from Chart.js V2.6.0 pie chart?
- How do i programmatically set bar fillColor in chartJs + angular
- chart.js add second line in a Line chart that starts from end of first line
- how I can get label name when user click on particular area in doughnut chart.js? I am not able to find the index of selected area for chart.js
- Group bar chart in ReactChartJS2 click particular element
- ChartJs different data for Tooltips
- Remove data text from Chart.js on hover
- Chart js how to remove numbers on circles of polar chart
- Chart.js - Mixed Chart: Bar Graph with Diagonal Line
- Add multiline labelString to yAxes Chart.js
- dynamic number of chart.js charts on the same page
- A chart Js error issue are occured in my Laravel other page?
- Chart.js in flex element overflows instead of shrinking
- Removing exceeding parts of axis
- Chartjs: How do you toggle the visibility of charts in Ionic 4
- Inserting and Fetching values from mongodb using nodejs and chartjs