JaRoi
JaRoi

Reputation: 65

Two models in backbone View

I have been trying to display two models in one view. Here is my code:

On router part- fetch models of about us and company and add them to 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

So the question is I want to display aboutus attributes such as aboutusId, description in template. How can i do that?

Upvotes: 0

Views: 140

Answers (2)

Kyle R
Kyle R

Reputation: 716

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

In these lines above, you create the var model but never add attach model to the AboutusView. Wouldn't you want to do:

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

In doing so, you have now a model, called model that has attributes aboutus and company, which you can access in your template by passing model.toJSON() in your template.

If Aboutus and Company are also models (I assume they are), you can access their attributes in your view by:

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

Upvotes: 0

Kyle R
Kyle R

Reputation: 716

Instead of sending this.model.toJSON() to your template, send both datasets (models). Keep in mind that you can send any type of JSON object to a template. You could do something like:

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

Then in your template you can access each model by <%= aboutus.description %> or <%=company.id %> (for example).

Upvotes: 1

Related Questions