主干JS。如何在视图加载后将纪元图表添加到视图

BackboneJS. How to add epoch chart to a view, when the view has loaded

我正在使用 BackboneJS 和 RequireJS,我想将纪元图表添加到视图中。

我有:

我的视图模板是:

<h1>Charts</h1>
<div id="gaugeChart" class="epoch gauge-small"></div>

我的路由器

showChart: function(){
  $('#page-wrapper').html(new ChartsView().el);
}

我的看法

/*global define*/
define([
  'jquery',
  'underscore',
  'backbone',
  'handlebars',
  'd3',
  'epoch',
  'text!templates/Charts.html'
], function($, _, Backbone, Handlebars, d3, epoch, templateSource) {
  var ChartsView = Backbone.View.extend({

    template: Handlebars.compile(templateSource),

    events: {
      'click #gaugeChart': 'hasRendered'
    },

    initialize: function() {
      this.render();
    },

    render: function() {
      this.$el.append(this.template());
      return this;
    },

    hasRendered: function() {
      $('#gaugeChart').epoch({
        type: 'time.gauge',
        domain: [1, 100],
        format: function(v) {
          return v.toFixed(0);
        },
        value: 1
      });

    }
  });
  return ChartsView;
});

在上面的 Backbone 视图中,我在 #gaugeChart 元素上有一个点击事件,这种方法有效,但是我如何触发加载事件,以便在加载视图时调用JavaScript函数添加纪元图表。 我试图在渲染功能完成后触发 hasRendered 功能,但这没有用。

最简单的方法可能是使用超时来延迟图表的呈现,以便它在呈现函数完成后执行。例如

render: function() {
      this.$el.append(this.template());

      setTimeout(function () {
        $('#gaugeChart').epoch({
             type: 'time.gauge',
             domain: [1, 100],
             format: function(v) {
               return v.toFixed(0);
              },
          value: 1
        });
      },0);

      return this;
    },

或者,您可以采取的另一种方法是让您的路由器在将您的 el 附加到 DOM 后调用视图的某些方法来呈现纪元图表,或者触发您的视图将使用的事件渲染图表。

例如

showChart: function(){
     var chartView = new ChartsView();
    $('#page-wrapper').html(chartView .el);

  //render chart directly
   chartView.renderChart(); //this assumes there is a "renderChart" method in your view
   //or trigger some event for view to respond to
  //chartView.trigger('atachedToDom'); //with your view subscribing to this event
}