I have a simple code that involves asynchronous tasks:
// 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 };
}
My requirement is that, onload
of NewsFeed needed to be executed in both case:
There's really no need to use new
or constructor
when you don't need new instances, all you really need is to run a simple ajax function that gets the result from cache if it hasn't changed.
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
});
});
The new pattern instead of callback is using Promises see: https://github.com/kriskowal/q
With jquery you can use: https://api.jquery.com/category/deferred-object/
now the code:
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: });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.