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个项目,但我看不到它们。
提前致谢
答案 0 :(得分:1)
我们需要查看更多代码才能提出更接近的建议,但希望这些解释可以帮到你。您应该将模型直接传递给集合,或者在获取中处理它。
//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);
}
});
});
});