简体   繁体   English

将多个模型绑定到骨干网中的单个视图

[英]Bind multiple models to a single view in backbone

I have 2 models as 我有2个型号

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');
     }
});

View is created as 视图创建为

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: 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>

How can we bind for both Info and Emp Models ? 我们如何绑定信息模型和Emp模型?

I dont really know how Backbone.ModelBinder(); 我真的不知道Backbone.ModelBinder(); work but i suppose that you have to create two binding; 工作,但我想你必须创建两个绑定;

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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM