2

如何连接更改模型中的某些字段以反映视图?我有一个持有字体粗细的模型,并且我在视图中看到了该模型,但是如何连接模型中字体粗细字段的更改以从视图中反映el

4

2 回答 2

6

有几种方法可以在这里应用,具体取决于您想要变得多么精致。

1. 模型更改时重新渲染整个视图

initialize: function(){
  this.model.on( "change", this.render, this );
}

2.更精确,只重新渲染需要的东西

initialize: function(){
  this.model.on( "change:title", this.renderTitle, this );
  this.model.on( "change:body", this.renderBody, this );
  this.model.on( "change:fontWeight", this.renderFontWeight, this );
}

这需要作为外科医生修改 DOM 的最小渲染方法公司:

renderTitle: function(){
  this.$el.find( "h1" ).html( this.model.get( "title" ) );  
},

renderBody: function(){
  this.$el.find( "p" ).html( this.model.get( "body" ) );  
},

renderFontWeight: function(){
  this.$el.find( "p" ).css( "font-weight", this.model.get( "fontWeight" ) );
}

3.对模型的每个部分使用子视图

我没有为这种方法提供任何示例,因为实现可能更复杂。试想一下,您的实际View实例是几个SubViews,一个用于title,另一个用于body,依此类推。每一个都有自己的render并绑定了其具体Model属性的变化以及该属性re-render何时发生变化。

您可以检查方法 1. 和 2 的工作 jsFiddle 代码。

于 2012-04-24T11:52:41.660 回答
1

尝试这个:

var Font = {};

Font.Model = Backbone.Model.extend({

    defaults: {
        font_family: 'Arial, Helvetica, sans-serif',
        font_size:   12,
        font_weight: 'normal'
    }
});

Font.View = Backbone.View.extend({

    initialize: function() {

        var this_view = this;

        this.model.bind('change:font_weight', function(model) {

            // Do something with this_view.el
            alert('handle the font-weight change');

        });
    }
});

var myFontModel = new Font.Model();

var myFontView = new Font.View({
    model: myFontModel
});

myFontModel.set({font_weight: 'bold'});
于 2012-04-24T10:34:43.777 回答