Search code examples
javascriptbackbone.jsunderscore.js

How to use Backbone Model to Multiple Views (in Multiple Files)?


I have simple HTML page, where I want to show multiple views with same data. For that I created one Backbone Model with data and two views to render. All my models and views are separated in separate files. I want to use my model object in all views. So I don't have to make multiple ajax calls to the server for same data for my 2 views.

Here is my code

Model.js

var ModelData = Backbone.Model.extend({
   defaults:{
      Name: "ABC",
      Marks: 100
   }
});

var modelData= new ModelData();

View1.js

var View1 = Backbone.View.extend({
   initialize: function(){
      this.model = (HOW TO REFER MY MODEL Object ?)
   }
});

View2.js

var View2 = Backbone.View.extend({
   initialize: function(){
      this.model = (HOW TO REFER MY MODEL Object?)
   }
});

Solution

  • From the fine manual:

    constructor / initialize new View([options])

    There are several special options that, if passed, will be attached directly to the view: model, collection, el, id, className, tagName, attributes and events.

    So you should attach the model when you instantiate your views:

    var v1 = new View1({ model: modelData });
    var v2 = new View2({ model: modelData });
    

    You should have a router or other object that takes care of instantiating your views. Whatever this thing is should keep track of the modelData model instance and then pass it to the views when instantiating them.