从backbone.js中的视图访问集合数据

时间:2011-08-19 04:13:58

标签: backbone.js

我完全坚持了解如何使用模型和集合。数据从服务器获取到集合中,但后来我不知道如何访问此数据以便在呈现时使用它

这是我的代码:

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

说,每个ImmoObject都有名字。我如何浏览集合中的所有元素(在渲染视图时)并输出其名称?我可以在StartPage.render()中执行类似的操作吗?

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

2 个答案:

答案 0 :(得分:2)

您可以使用underscore.js的each方法:

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

在您的路由器中:

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();将在集合上触发reset事件,该事件将重新呈现StartPage视图。

答案 1 :(得分:0)

是的,您可以在render方法中执行此操作。 或者在应用程序视图的addOne方法中。

addOne方法接收模型(如果你的应用程序代码接近演示),你应该在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);
},

希望这有帮助。

相关问题