0
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 个项目,但我没有看到它们。

提前致谢

4

1 回答 1

1

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

//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);
                  }
             });
        });
    });
于 2013-02-26T21:44:18.603 回答