[英]Callback called when a task finish OR already finished
我有一个涉及异步任务的简单代码:
// 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
新闻推送的需要在这两个情况下要执行:
当您不需要新实例时,真的没有必要使用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
});
});
使用 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: });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.