Search code examples
backbone.js

accessing collection data from view in backbone.js


I got fully stuck truing to understand how should I work with models and collections. Data is fetching from server into collection but then I do not know how to access this data in view to use it while rendering

here is my code:

ImmoObject = Backbone.Model.extend();

Realty = Backbone.Collection.extend({
    model: ImmoObject,
    url: 'getall',

    initialize: function(){
        this.fetch();
    }
});

Application = Backbone.Router.extend({
    _realty: null,
    _view: null,
    routes: {
        "": "index",
        //"details": "details"
    },

    initialize: function(){
        this._realty = new Realty();
        if (this._view === null){
            this._view = new StartPage({collection: this._realty});
        }
    },

say, each ImmoObject have name. how I can go through all elements in collection (while rendering view) and output their names? Can I do something like this in StartPage.render()?

$.each(this.collection, function(k, v){
console.log(v.name);
})

Solution

  • You can use the each method of underscore.js :

    StartPage = Backbone.View.extend({
      el: $("#ul-immo-list"),
    
      initialize: function() {
        _.bindAll(this, "render");
        this.collection.bind('reset', this.render);
      },
      ...
      render: function() {
        this.collection.each(function(immoObject) {
          console.log(immoObject.name);
          this.el.append("<li>" + immoObject.name + "</li>")
        }
      }
    });
    

    And in your router :

    Application = Backbone.Router.extend({
      _realty: null,
      _view: null,
      routes: {
        "": "index",
      },
    
      initialize: function(){
        this._realty = new Realty();
        if (this._view === null){
          this._view = new StartPage({collection: this._realty});
        }
        this._realty.fetch(); 
      },
    });
    

    this._realty.fetch(); will fire a reset event on the collection, which will re-render the the StartPage view.