Backbone.js视图在其创建过程中的生命周期

时间:2012-08-14 20:45:04

标签: javascript jquery backbone.js

我是backbone.js的新手,也是前端工作的新手,还没有弄清楚生命周期是如何工作的。

我们有一个Django后端,它为我们提供了html模板,我们基本上只用作框架。所有逻辑都在Backbone视图中处理。

我目前遇到的问题是我正在尝试绘制图形但是图形功能找不到基于id的视图,因为它在渲染功能期间不存在,但我不知道一种在以后阶段实现这一目标的方法。

我已经尝试在页面完全加载后在Chrome控制台中手动创建视图并且它可以正常工作:

   var main = new MainView();
   main.showChart();

观点:

   var ChartView = Backbone.View.extend({

     title: 'Chart',

     initialize: function() {

    // This assures that this refers to this exact view in each function
    // (except within asynchronous functions such as jquery each)
    _.bindAll(this);

    // Saving parameters given by parent
    this.index = this.options.index;

    // Retrieve the template from server
    var template = _.template(getTemplate('chart.html'));

    // Compile the template with given parameters
    var compiledTemplate = template({'title': this.title});

    // Set the compiled template to this instance's el-parameter
    this.$el.append(compiledTemplate);

    // Rendering the view
    this.render();
 },

   render: function() {

    var self = this;

    // Draw the graph when the page is ready
    $(function(){
        self.drawGraph('chart1', this.line1Data);
    });

    // Render function should always return the instance
    return this;
},

drawGraph : function(chartId, lineData) {

    Morris.Line({
          element: chartId,
          data: [
            {y: '2012', a: 100},
            {y: '2011', a: 75},
            {y: '2010', a: 50},
            {y: '2009', a: 75},
            {y: '2008', a: 50},
            {y: '2007', a: 75},
            {y: '2006', a: 100}
          ],
          xkey: 'y',
          ykeys: ['a'],
          labels: ['Series A']
    });
},

});

创建地点:

     var chartWidgetView = new WidgetView({'contentView': new ChartView()});
    this.initializeWidget(chartWidgetView);
    this.$el.append(chartWidgetView.el);

有人可以向我澄清:

  1. Backbone如何实际处理视图的创建?有哪些不同的阶段?
  2. 我应该如何处理这种情况,例如:在我的代码的哪一点,html模板中的元素是否存在,以便我可以为它调用图形函数?
  3. 或者我的架构是否存在根本缺陷?我应该尝试以完全不同的方式做到这一点吗?

3 个答案:

答案 0 :(得分:11)

FWIW,我认为你走在正确的轨道上。但正如你的问题所指出的那样,你只是有些事情没有问题。

严格地说,骨干视图中没有很多生命周期。实例化一个时,它会调用initialize。除此之外,由您决定视图的生命周期。什么时候会呈现。当渲染的el将附加到DOM时,它将从DOM中删除,何时将被关闭并销毁。这一切都取决于您希望如何使用视图。

当然,您可以执行一些操作并添加内容,以使此生命周期更容易理解。例如,有一些很好的框架位于主干之上。我建议将LayoutManager,Thorax,Chaplin和我自己的Marionette作为起点。

更重要的是,您所描述的插件很可能依赖于插件运行之前DOM中的HTML元素。这对于可视插件来说很常见,因为它们通常需要捕获位置信息,css信息,相关项目的位置等。

您可以采取一些非常简单的方法来促进这些类型的插件并使其工作。我在博客上写了一点,在这里:http://lostechies.com/derickbailey/2012/02/20/using-jquery-plugins-and-ui-controls-with-backbone/ - 希望这会帮助你走上正轨。

具体来说,您需要了解的是onShow方法的概念。这不是Backbone自己理解的方法。这是一个您必须添加到您的视图和应用程序的概念。但好消息是它很容易。只需将方法添加到视图中,然后在合适的时间调用它:


var AnotherView = Backbone.View.extend({
  onShow: function(){
    this.$el.layout({ appDefaultStyles: true});
  }
});


// instantiate the view
var view = new AnotherView();

// render it
view.render();

// attach it to the DOM
$("#someDiv").html(view.el);

// now that it has been attached to the DOM
// you can call your DOM-dependent plugins
view.onShow();

希望有所帮助。

答案 1 :(得分:1)

只是看了一眼我认为问题是在呈现模板之前不会从服务器返回模板,因此它不会出现。您可以使用jQuery的deferred对象解决此问题(请参阅this ref)。尝试在initialize结束时做一些事情:

this.deferredTemplate = $el.append(compiledTemplate);

this.deferredTemplate.done(function() {
  this.render();
});

另见Derick Bailey关于backbone.js中延迟的文章:http://lostechies.com/derickbailey/2012/02/09/asynchronously-load-html-templates-for-backbone-views/

答案 2 :(得分:1)

你正在创建el而不是将它附加到DOM,我怀疑图表只搜索DOM以便将元素附加到其中。在调用drawGraph之前,您需要将它附加到DOM。

至于Backbone视图的创建,我认为获得深入视图的最佳方法是简单地阅读带注释的源代码,实际上并不长。