[英]Add .done() callback to custom function
我將這些功能包含在一個小類中:
var Ajax = {
// Send new entry data to database
endNewEntry: function (json) {
$.post("/controllers/insertEntry.ajax.php", {"json": json});
},
loadView: function (view, target, extra) {
var input = $.extend({}, {"view": "../" + view}, extra) || {"view": "../" + view};
$.get("/controllers/loadView.ajax.php", input, function (data) {
$(target).replaceWith(data);
});
}
};
如您所見,這兩個函數都使用jQuery $.ajax
對我的服務器執行請求,並用響應替換我的部分文檔。
現在,我想在這些函數中添加一個功能,以便在發布請求完成后讓我調用另一個函數(回調)。
我想要這樣的語法:
Ajax.loadView(view, target, extra).done( function() { something; });
相反,我知道的唯一方法是向定義了回調函數的loadView
添加另一個參數,但是我想擁有.done()
函數。
我能怎么做?
done
是promise API的一部分。
承諾是對流控制的抽象,它使您可以“更同步”的方式編寫異步代碼。
一個promise對象具有一個.then
方法,該方法允許您將操作鏈接到該對象,並且保證每個操作僅在上一個操作完成時才終止。
myAjax().then(function(result){
// do something with result, myAjax done here
return otherAjax();
}).then(function(otherResult){
// otherAjax done here, this only gets called after the above code handling myAjax is done
});
Promise實現(至少其中一些)包括一個.done
方法(類似於.then
,然后將錯誤記錄到控制台,而不是讓您在Promise鏈中處理它們(Promise可以做的另一件事)。
您可以根據情況簡單地返回承諾:
var Ajax = {
// Send new entry data to database
endNewEntry: function (json) {
return $.post("/controllers/insertEntry.ajax.php", {"json": json});
},
loadView: function (view, target, extra) {
var input = $.extend({}, {"view": "../" + view}, extra) || {"view": "../" + view};
return $.get("/controllers/loadView.ajax.php", input, function (data) {
$(target).replaceWith(data);
});
}
};
哪個可以讓您做:
Ajax.loadView().done(function(data){
//do something with the result, in variable data here.
});
當然,您可以像上面所示的那樣將事物鏈接到它,以執行多個異步操作。 jQuery還提供$.when
等待多個承諾。
值得一提的是,那里有更好,更快和更強大的promise實現。
由於$.get
返回一個promise
(假設您使用的是jQuery> = 1.7),只需返回,您就可以訪問后面的屬性:
return $.get("/controllers/loadView.ajax.php", input, function (data) {
$(target).replaceWith(data);
});
而且我會親自處理$(target).replaceWith(data);
同樣在done()
回調中,以避免混淆。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.