SET001
SET001

Reputation: 11718

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

Upvotes: 0

Views: 1170

Answers (2)

Tricote
Tricote

Reputation: 1508

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.

Upvotes: 2

theprogrammer
theprogrammer

Reputation: 2734

Yes you can do it in the render method. Or in the addOne method of the application view.

The addOne method receives the model (if you keep your application code close to the demos) you should have something like this in AppView.

addOne: function(immo) {
  var name = immo.name; //Accesing the name for the model here
  var view = new ImmoView({model: immo});
  this.$("#todo-list").append(view.render().el);
},

Hope this helps.

Upvotes: 0

Related Questions