骨干视图中的两个模型

时间:2014-01-22 11:25:44

标签: backbone.js requirejs backbone-views backbone-model

我一直试图在一个视图中显示两个模型。这是我的代码:

在路由器上获取关于我们和公司的模型,并将它们添加到AboutusView:

var self=this;
var aboutus=new Aboutus({id:1});
var company= new Company({id:1});
aboutus.fetch();
company.fetch();


var model = new Backbone.Model();
model.set({aboutus: aboutus, company: company});
var aboutusView=new AboutusView({model:aboutus,model2:company});
aboutusView.render();
self.changePage(aboutusView);


=======================

For Aboutus View Part:


var AboutusView = Backbone.View.extend({

template: _.template(aboutusViewTemplate),

initialize: function () {
    _.bindAll(this, 'render');

},


render: function(){

console.log(this.model);
console.log(this.options.model2);


this.$el.html(this.template(this.model.toJSON()));

  return this;
}
});

return AboutusView;




============================
In console log of this.model (aboutus) is:
===========================
 child {attributes: Object, _escapedAttributes: Object, cid: "c0", changed: Object,     _silent: Object…}
 _changing: false
 _escapedAttributes: Object
 _pending: Object
 _previousAttributes: Object
 _silent: Object
  attributes: Object
     aboutusId: 1
     description: "testing" 
      id: 1
       imageExtension: ""
       title: "ABOUT US"
 __proto__: Object
 changed: Object
  cid: "c0"
  id: 1
 __proto__: ctor

所以问题是我想在模板中显示aboutusId,description中的aboutus属性。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

不是将this.model.toJSON()发送到模板,而是发送两个数据集(模型)。请记住,您可以将任何类型的JSON对象发送到模板。你可以这样做:

var somedata = {
    aboutus: this.model.toJSON(),
    company: this.options.model2.toJSON() //or 'this.model2.toJSON()', not completely sure where this model is accessible in the view.
    }

this.$el.html(this.template(somedata));

然后,在您的模板中,您可以<%= aboutus.description %><%=company.id %>(例如)访问每个模型。

答案 1 :(得分:0)

var model = new Backbone.Model();
model.set({aboutus: aboutus, company: company});
var aboutusView=new AboutusView({model:aboutus,model2:company});

在上面的这些行中,您创建了var model,但从未向model添加附件AboutusView。你不想这样做:

var aboutusView=new AboutusView({model:model});

这样做,您现在拥有一个名为model的模型,其中包含aboutuscompany属性,您可以在模板中访问model.toJSON()模板。

如果Aboutus和Company也是模型(我认为它们是),您可以通过以下方式访问视图中的属性:

this.model.get('aboutus').get('id')