【问题标题】:Bind multiple models to a single view in backbone将多个模型绑定到主干中的单个视图
【发布时间】:2015-10-01 18:03:45
【问题描述】:

我有两个模型

var Info = Backbone.Model.extend({
     defaults: {
        name: '',
        company: ''
     },
     initialize: function(){
        console.log('Object of type Info created');
     },
});

var Emp = Backbone.Model.extend({
     defaults: {
        empId: '',
        empGroup: ''
     },
     initialize: function(){
        console.log('Object of type Emp created');
     }
});

视图被创建为

var model = new Info();
model.set({
    name: 'John',
    company: 'ABC'
});
model.bind('change', function(){
    model.save();
});
model.trigger('change');


var ViewClass = Backbone.View.extend({
     _modelBinder: undefined,
     initialize: function(){
         this._modelBinder = new Backbone.ModelBinder();
         this.render();
     },
     render: function(){
         var template = _.template($('#App1').html());
         this.$el.html(template);
         var bindings = {
             name: '[name=name]',
             empId: '[name=empId]'
         };
         this._modelBinder.bind(model, this.el, bindings);  // this will bind for Info. 
     }
});

HTML:

<script type="text/template" id="App1">
<div id="wrapper">
    Name: <input type="text" name="name" /><br />
    EmpId: <input type="text" name="empId" />
</div>
</script>

我们如何绑定 Info 和 Emp 模型?

【问题讨论】:

    标签: javascript backbone.js model-binders


    【解决方案1】:

    我真的不知道Backbone.ModelBinder(); 是如何工作的,但我想你必须创建两个绑定;

    var infoBindings = {
             name: '[name=name]',
         };
         this._modelBinder.bind(infoModel, this.el, infoBindings);  // this will bind for Info.
    
     var empBindings = {
             empId: '[name=empId]'
         };
         this._modelBinder.bind(empModel, this.el, empBindings);  // this will bind for Emp.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-04
      • 1970-01-01
      • 1970-01-01
      • 2014-11-29
      • 1970-01-01
      相关资源
      最近更新 更多