[英]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.