在我的Backbone视图初始化中,我调用了一个重写的fetch。 Fetch检查数据是否在localStorage中,如果不是,则使用ajax拉取数据并填充到localStorage中。
但是,ajax调用需要一些时间,因此fetch方法在ajax完成之前返回。因此,原始提取调用永远不会触发成功事件。
如何从fetch中触发成功事件?我还需要传递数据(一旦ajax完成)进行初始化(以某种方式返回它,或者再次使成功事件调用fetch()从localStorage拉出来。)
谢谢!
在appview中初始化:
initialize: function() {
var imageList = new ImageList(),
simageel = $(this.el).find('#imagec'),
simageView;
imageList.fetch({
error: function() { console.log(arguments); },
success: function(collection) {
collection.each(function (model) {
simageView = new SImageView({
model: model
});
simageel.html(simageView.render().el);
console.log('Fetch success.'); // Never fires
});
}
});
在集合中重写了抓取:
fetch: function(options) {
if(!localStorage.getItem("image")) {
var self = this;
$.ajax({
url: '[url]' //Could add async but how to trigger render from this function?
}).done(function(response) {
console.log("Fetched");
$.each(response.items, function(i, item) {
self.create(item); // saves model to local storage
});
}).fail(function(response) {
console.log("Failure in fetch");
});
} else {
// fetch from localStorage works fine
return Backbone.Collection.prototype.fetch.call(this, options);
}
}
答案 0 :(得分:0)
fetch: function(options) {
if(!localStorage.getItem("image")) {
var self = this;
$.ajax({
url: '[url]' //Could add async but how to trigger render from this function?
}).done(function(response) {
console.log("Fetched");
$.each(response.items, function(i, item) {
self.create(item); // saves model to local storage
});
options.success(self); //call success func
self.trigger('sync', self, response, options); //fire sync event
}).fail(function(response) {
console.log("Failure in fetch");
options.error(responce) //call error func
});
} else {
// fetch from localStorage works fine
return Backbone.Collection.prototype.fetch.call(this, options);
}
}
一旦开始使用像$ .ajax这样的异步函数,就不能使用返回值作为下一个方法。你需要调用回调函数。
模型/集合完成提取时,原始Backbone fire sync
事件。
所以在你的代码中做同样的事情。并在View构造函数中执行listenTo
以运行下一个方法。
initialize: function() {
var imageList = new ImageList(),
simageel = $(this.el).find('#imagec'),
simageView;
this.listenToOnce(imageList,"sync",function(){
console.log("call next method what you want to do after fetching's finished");
});
imageList.fetch({
error: function() { console.log(arguments); },
success: function(collection) {
collection.each(function (model) {
simageView = new SImageView({
model: model
});
simageel.html(simageView.render().el);
console.log('Fetch success.'); // Never fires
});
}
});