backbone.js 视图的初始化功能

示例

initialize 构造视图后,Backbone会立即调用它。

可选参数

该initialize函数接收传递给视图构造函数的所有参数。通常,用于传递视图默认选项的options哈希:

['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events']

您可以将任何自定义属性添加到选项哈希和/或自定义参数。

var MyView = Backbone.View.extend({
    initialize: function(options, customParam){
        // 确保“选项”是一个哈希,以避免未定义的错误。
        options = options || {};
       this.customAttribute= options.customAttribute;
       this.customParam= customParam;
    },
});

并构造视图:

var view = new MyView({
    model: new Backbone.Model(),
    template: "<p>a template</p>",
    customAttribute: "our custom attribute"
}, "my custom param");

请注意,所有默认视图选项都会自动添加到视图对象,因此无需在initialize函数中执行此操作。

立即渲染图案

该initialize方法的一种常见模式是调用该render方法,以便立即渲染任何新构造的View

仅当构造对象应立即将其呈现到HTML文档,绑定所有事件侦听器并执行与在DOM中放置内容相关的所有其他操作时,才使用此模式。

var MyView = Backbone.View.extend({
    initialize: function() {
        this.render();
    },

    render: function() {
        this.$el.html("<p>I'm running!</p>");
    }
});

但是,应注意,在手动(或通过其他方法)调用之前,不应立即渲染某些视图.render。

另一个常见的initialize模式是将内容添加到View对象中,稍后将需要这些内容:

var MyView = Backbone.View.extend({
    el: "body",
    template: _.template( "<p>This is <%= name %>'s page</p>" ),

    initialize: function(){
       this.name= "Bill";
        
        this.render();
    },

    render: function(){
        var viewTemplateData = {
            name: this.name
        };

        this.$el.html( this.template( viewTemplateData ) );
    }
});

DOM现在将包含<p>This is Bill's page</p>在中body。