当没有来自JSON的数据时,饼图崩溃

时间:2016-08-30 17:54:22

标签: javascript rest backbone.js charts chart.js

我是初学者并且正在学习网络开发。在我的示例项目中,我使用ChartJS创建了饼图。我从REST服务获取数据。一切都很好,饼图正在正确呈现。问题是当REST中存在空数据时,我在Chart.js中出现错误。

错误: enter image description here

来自REST的JSON数据: enter image description here

我的示例项目使用BackboneJS。我知道错误是因为没有来自REST的数据。如何处理,以便饼图不会崩溃。 以下是MODEL:

define(['backbone'], function(Backbone) {
    var chart = Backbone.Model.extend({
        urlRoot: 'SAMPLE REST URL',
        defaults: function() {
            return {
                currMonthOccAvailVac: [],
            };
        },
        fetch: function(data) {
            var d = $.Deferred();
            var self = this;
            var ajaxRequest = $.ajax({
                url: this.urlRoot,
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: JSON.stringify(data)
            });
            ajaxRequest.done(function(json) {
                var graphVar = {
                    currMonthOccAvailVac: [],
                }
                var yearSelected = (localStorage.getItem('date')).split("-")[0];
                var monthSelected =  (localStorage.getItem('date')).split("-")[1];
                for (var i = 0; i < json.length; i++) {
                    var monthYear = json[i].columnstrDate.split("/");
                    var year = monthYear[0];
                    var month = monthYear[1];
                    if(month.length == 1)
                    if(month == (monthSelected - 1) && year == yearSelected)
                    {
                        graphVar.currMonthOccAvailVac.push(json[i].columndecOccPercentage);
                        graphVar.currMonthOccAvailVac.push(json[i].columndecVacantUnitsPercentage);
                        graphVar.currMonthOccAvailVac.push(json[i].columndecUnavailableUnitsPercentage);
                    }
                }
                self.set({
                    currMonthOccAvailVac: graphVar.currMonthOccAvailVac,

                });
                d.resolve();
            });
            //failure callback for ajax request.
            ajaxRequest.fail(function(jqXHR, status) {
                // Handle fail request
                d.reject();
            });
            return d.promise();
        }
    });
    // returning the model
    return {
        chart: chart
    };
});

放入ChartJS实际代码中断的地方:

enter image description here

那么即使graphvar.currMonthOccAvailVac没有价值,我怎样才能确定饼图不会崩溃。请指导我。

修改

目前在我的View模型中,我做了类似下面的操作。但我不确定这是否是正确的处理方式。

define(['backbone'], function(Backbone) {
  var sixthSubViewModel = Backbone.View.extend({
    template: _.template($('#myChart6-template').html()),
    render: function() {
      $(this.el).html(this.template());
      var ctx = this.$el.find('#pieChart')[0];
      var data = {
        datasets: [{
          data: this.model.attributes.currMonthOccAvailVac,
          label: 'My dataset' // for legend
        }],
        labels: [
          "Rented",
          "Vacant",
          "Unavailable",
        ]
      };
      // I AM CHECKING HERE THE LENGTH AND THE RNEDERING THE PIE CHART
      if (this.model.attributes.currMonthOccAvailVac.length > 1)
        var pieChart = new Chart(ctx, {
          type: 'pie',
          data: data,
          otpions: {
            legend: false
          }
        });
      WHAT SHALL I PUT IN THE ELSE PART
    },
    initialize: function() {
      this.render();
    }
  });
  return sixthSubViewModel;
});

0 个答案:

没有答案