Backbone js:从模板访问View变量

时间:2014-04-14 20:19:17

标签: ruby-on-rails backbone.js

我是Backbone js的新手,我写了一段这样的代码;

Skymama.Views.UsersIndex = Backbone.View.extend({

  template: JST['users/index'],
  render: function() {  
    var allUsers = new Skymama.Collections.Users();
    allUsers.fetch();   
    this.$el.html( this.template({users: allUsers }) );
    return this;
  },

});

如何在类似的内容中访问模板中allUsers的值;

<% _.each(users, function(user){ %>

<% }); %> 

1 个答案:

答案 0 :(得分:2)

fetch()是一个异步方法,你应该在fetch()完成后调用render。

通常你想在你的视图中初始化你的收藏品

initialize: function () {
   this.collection = new Skymama.Collections.Users([]);
   this.collection.fetch({reset: true});

   this.listenTo(this.collection, 'reset', this.render);
},

render: function () {
    this.$el.html( this.template({users: this.collection }) );
    return this;
} 

&#39;重置&#39;当fetch()成功时,将在集合上触发事件。

您也可以将this.render附加到fetch作为其回调

来执行此操作
  this.collection.fetch().done(this.render);

但如果你喜欢这样做,你会想要将渲染的上下文绑定到视图

  initialize: function () {
      _.bindAll(this, 'render');

      //...
  }