在主干上填充集合

populate collection on Backbone

本文关键字:填充 集合      更新时间:2023-09-26
Tutorial.Views.Layout = Backbone.Layout.extend({
  model: Tutorial.Model,
  });
initialize: function () {
  _.bindAll(this);
  this.model = new Tutorial.Model({id : $("#data").data('user') });
  this.collection = new Tutorial.Collection();
  var success1 = function(){
         console.log('OK');
     };
     this.collection.fetch({success : success1});
},
showTuto: function(){
  step = this.collection.first(1);
  console.log(step);
},

我的问题是集合是空的。我的模型有4个项目,但是我一个都没看到。

Thanks in advance

我们需要看到更多的代码来做出更接近的建议,但希望这个解释将帮助您。你应该将你的模型直接传递给集合,或者在获取中处理它。

//simplified view
YourView = Backbone.View.extend({
    initialize : function(){
         var testModel = new Tutorial.Model({id : $("#data").data('user') });
         this.collection = new Tutorial.Collection();
         this.collection.add(testModel);
    }
});
在这种情况下,您将直接将该模型添加到您的集合中。如果您想异步调用并从fetch获取数据,然后传递回调,您可以这样做:
//simplified view
    YourView = Backbone.View.extend({
        initialize : function(){
             this.collection = new Tutorial.Collection();
             this.collection.fetch(function(){
                  console.log('okay');
             });
        }
    });
    Tutorial.Collection = Backbone.Collection.extend({
        fetch : function(callback){
             // grab a ref to your collection
             var thisCollection = this;
             // call your data function which has the ajax call
             getYourDataFunction(function(data){
                  // if your data returned is an array of objects
                  thisCollection.add(data);
                  if (typeof callback === "function"){
                       //if you included a callback, call it with a reference to the collection
                       callback.call(thisCollection);
                  }
             });
        });
    });