我有一个涉及异步任务的简单代码:
// The NewsFeed Class
function NewsFeed() {
this.loadFeed = function() {
$.ajax({
url: "http://www.example.com",
success: function() {
// doSomething here, and call onload.
}
});
}
// Need to implement onload here somehow
this.onload = ?;
this.loadFeed();
return this;
}
NewsFeed.constructor = NewsFeed;
// In main JS file
var newsFeed = new NewsFeed();
$(function() {
// do something
newsFeed.onload = function() { // do something when news feed is loaded };
}
我的要求是,在两种情况下都需要执行onload
的NewsFeed:
答案 0 :(得分:0)
当你不需要新的实例时,真的没有必要使用new
或constructor
,你真正需要的只是运行一个简单的ajax函数,如果它没有,则从缓存中获取结果改变了。
function newsFeed() {
return $.ajax({
url : "http://www.example.com",
cache : true // let the browser handle caching for you
});
}
// In main JS file
$(function() {
newsFeed().then(function() {
// do something when news feed is loaded
});
});
答案 1 :(得分:0)
新模式而不是回调是使用Promises 看到: https://github.com/kriskowal/q
使用jquery,您可以使用: https://api.jquery.com/category/deferred-object/
现在代码:
function NewsFeed() {
function loadFeed() {
var deferred = $.Deferred();
$.ajax({
url: "http://www.example.com",
success: function(data) {
deferred.resolve(data);
},
error: function(data) {
deferred.reject(data);
}
});
return deferred.promise();
}
this.loadFeed = loadFeed;
return this;
}
NewsFeed.constructor = NewsFeed;
// In main JS file
var newsFeed = new NewsFeed();
newsFeed.loadFeed().done(function(data){
//data loaded successfully
})
.fail(function(data){
//ajax request failed
})
.always(function(){
//finally:
});