-1

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:

  • If the loadFeed's ajax is finished, run it immediately.
  • If the loadFeed's ajax is not done yet, run after it.
Luke Vo
  • 17,859
  • 21
  • 105
  • 181
  • `this.loadFeed();` will throw an error. but anyway it sounds like you're describing what a promise does. It will execute a callback when done, and if you add another callback after it is done it will be called immediately with the result. – Kevin B Sep 16 '16 at 15:14
  • Thanks, it was by bad. It should be `this.loadFeed = function()` – Luke Vo Sep 16 '16 at 16:54

2 Answers2

0

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 
    });
});
adeneo
  • 312,895
  • 29
  • 395
  • 388
0

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:
});
SantiG
  • 788
  • 6
  • 7
  • this is a very common anti-pattern... `$.ajax` already returns a promise, there is no need to create a new one – charlietfl Sep 16 '16 at 15:26
  • see http://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it – charlietfl Sep 16 '16 at 15:33