簡體   English   中英

將多個模型綁定到骨干網中的單個視圖

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

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

視圖創建為

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>

我們如何綁定信息模型和Emp模型?

我真的不知道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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM