将多个集合注入视图(模板)Backbone JS

时间:2014-09-11 14:51:14

标签: backbone.js backbone-collections

我想知道是否有可能在获取后将多个集合传递到视图中,例如:

 Collection1 = new Collections.Collection();
 Collection1.fetch({
    success: function (collection) {
        //save it somewhere 
    }
 });

 Collection2 = new Collections.Collection();
 Collection2.fetch({
    success: function (collection) {
        //save it somewhere 
    }
 });

所以一旦它们被加载了......渲染我的视图(同样,Idk如何等到两个都被提取,所以任何帮助都会受到赞赏)。

var template = _.template( $('#myTemplate').html(), { col1: collection1, col2 : collection2 } ) ;

这是否可行?如果不是,如果我需要在模板中访问不同的集合值,我该怎么办?

先谢谢你!

2 个答案:

答案 0 :(得分:2)

Backbone .fetch返回一个promise对象,您可以使用$.when

$.when(firstCollection.fetch(), secondCollection.fetch()).then(function () {
    //both are fetched
});

答案 1 :(得分:1)

是的,如果您的模板已准备好与col1col2一起使用,则可以在视图中加载这两个集合,并设置事件侦听器,以便在其中任何一个准备就绪时重新呈现:

var MyDoubleColView = Backbone.View.extend({
  initialize: function(options){
    this.firstCollection = new Collections.Collection();
    this.secondCollection = new Collections.Collection();
    this.listenTo(this.firstCollection, "reset", this.render);
    this.listenTo(this.secondCollection, "reset", this.render);

   this.firstCollection.fetch({reset:true});
   this.secondCollection.fetch({reset:true});
  },
  render: function(){
    var template = _.template( $('#myTemplate').html(), 
      { col1: this.firstCollection.toJSON(), col2 : this.secondCollection.toJSON() }) ;
  }
});

当任何集合从服务器中水合时,这将导致视图重新呈现。我已经使用了reset事件,但您可以使用任何其他与收集服务器相关的事件,例如sync

让你的模板准备好收集空白,你会很高兴。 :)

相关问题