_.bindAll函数

时间:2012-05-21 18:18:27

标签: backbone.js backbone-views

我的问题很可能需要一个非常简单的答案,然而,我无法轻易找到答案。

我正在处理的Backbone应用程序有几个视图。在定义不同的视图时,我在initialize函数中使用_.bindAll将“this”视图对象与视图的render函数连接起来。例如:

DiscussedItemView = Backbone.View.extend({
    ...
        initialize: function() {
            _.bindAll(this, "render");
        },


        render: function() {    

            this.$el.attr('id', 'li-meeting-task-' + this.model.getId());

            this.$el.html(JST['tasks_sandbox/agenda_task_item']({ 
                taskName    : this.model.getName(),
                taskId      : this.model.getId()
            }));

            return this;
        },
    ...
});

要创建DiscussedItemView的新实例,请执行以下操作:

...
        var discussion_agenda_row = new DiscussedItemView({model: task});
        discussion_agenda_row.render();
        this.$( '#meeting-items-list' ).append(discussion_agenda_row.$el); 
...

代码工作正常。不过,我不明白为什么需要在discussion_agenda_row上明确使用render()函数。我认为新的DiscussedItemView实例的初始化会自动调用render函数,但如果删除discussion_agenda_row.render();行,则不会显示HTML。我错在哪里?

谢谢你, 珊

2 个答案:

答案 0 :(得分:2)

不,render不会自动调用initialize。应用程序中的其他组件(例如路由器或其他视图)将告诉您查看何时呈现自己。

答案 1 :(得分:1)

视图会响应模型中的更改。在您的代码中,您没有对模型进行更改,因此视图没有响应。您还没有将视图设置为模型更改的侦听器。你在初始化中可以做的是这样的事情:

initialize : function() {
    //this will tell the view to render when the model 
    //triggers a "change" event
    this.model.on("change", this.render, this);

    //this will make the model throw the change event
    //and since the view is listening to "change," render will be invoked.
    this.model.fetch();
}

所有这一切,如果您没有进行任何提取并且数据就在您的模型中,您仍然必须显式调用view.render()。在任何情况下,对于良好的MVC,我仍然会让视图听取模型中的更改,以便在响应中正确更新自己。