有没有办法将Model的.change()触发器绑定到View的.render()函数而不创建多个?

时间:2011-08-16 01:39:38

标签: backbone.js

View通常需要具有这些属性的对象才能呈现:

{ el: '#someelement', model: someModel }

View还允许我们将模型的事件绑定到视图中的函数:

initialize: function() {
    this.model.bind('change', this.renderFromModel, this);
},

render: function() {
    $(this.el).html(this.template(this.model.toJSON()));
    return this;
},

renderFromModel: function() {
    var t = _.template($('#some-template').html());
    $('item-' + this.cid).html(t(this.toJSON()));
    return this;
},

问题是我们第一次实例化一个View for rendering时,它期待一个带有Model的对象;第二次从模型中调用它时渲染视图,它不是。因此,我最终创建了两个render()函数。

是否有更好的方法来实现单项渲染,也可以响应model.change()事件?

5 个答案:

答案 0 :(得分:39)

我认为您需要通过调用underscore.js的bindAll方法来确保您的render方法始终绑定到视图。

SomeView = Backbone.View.extend({
  initialize: function(){
    _.bindAll(this, "render");
    this.model.bind('change', this.render);
  },

  render: function(){
    $(this.el).html(this.template(this.model.toJSON()));
    return this;
  }
});

答案 1 :(得分:13)

更好的解决方案是使用listenTo function

SomeView = Backbone.View.extend({
  initialize: function(){
    this.listenTo(this.model, 'change', this.render);
  },

  render: function(){
    this.$el.html(this.template(this.model.toJSON()));
    return this;
  }
});

这样,视图对象就知道它所做的绑定,并且所有这些绑定都可以使用stopListening function删除,并且不需要显式调用bind或bindAll。最后但并非最不重要的是,我认为代码更清晰。

答案 2 :(得分:12)

使用_.bind()方法设置范围

 this.model.bind('change', _.bind(this.render, this));

答案 3 :(得分:6)

从Backbone 0.9.2开始(可能更早),on()bind()函数(以及其对应off()unbind())采用可选{调用context时使用的{1}}参数。

所以,

this

可以成为

SomeView = Backbone.View.extend({
  initialize: function(){
    _.bindAll(this, "render");
    this.model.bind('change', this.render);
  },

  render: function(){
    this.$el.html(this.template(this.model.toJSON()));
    return this;
  }
});

请参阅the documentation for on()

答案 4 :(得分:0)

在视图中创建模型实例

var myapp.myView  = new View({
        model: new Model
    });

当你初始化Backbone.View里面添加这个..这个渲染将被调用任何时候有变化是模型属性从它的默认值

this.model.bind('change', this.render,this)