1

I have this code for a newsfeed that I want to use.

I want it to look kind of like this:

function News(){

    //Load new comments every 5 sec
    setTimeout((function(){
        console.log(this); //Returns Object #News
        this.loadNewsFeed();
    }).call(this),5000);

    this.loadNewsFeed = function(){
        // Implementation here
    }
}

The problem here is that it says the Object News doesn't have an method called loadNewsFeed!

I've already got it to work if I put the anonymous function outside the object News.

Like this:

var news = new News();
//Load new comments every 5 sec
(function loopNews(){
    news.loadNewsFeed();
    setTimeout(loopNews,5000);
})();

So how can I do this inside the object News?

I Hate Lazy
  • 47,415
  • 13
  • 86
  • 77
Muqito
  • 1,369
  • 3
  • 13
  • 27

1 Answers1

3

This should work:

function News()
{
    var self = this;

    this.loadNewsFeed = function(){
        // Implementation here
    };

    //Load new comments every 5 sec
    setInterval(function handler() // setInterval for endless calls
    {
        console.log(self); //Returns Object #News
        self.loadNewsFeed();
        return handler;
    }(), 5000);
}

Explanation:
call(this) invokes the handler directly - and returns undefined to setInterval which means that it's executed immediately but no handler is set.
The handler-function executes in global context so this is the window-object. The local variable self "injects" the current (and desired) this - as self.

Edit 2:
Now executes immediately and registers a handler.

David Rettenbacher
  • 5,088
  • 2
  • 36
  • 45
  • This question was asked just yesterday - see here: http://stackoverflow.com/questions/13771889/setinterval-with-self-executing-function – David Rettenbacher Dec 10 '12 at 20:26
  • Hmm, after your update @Warappa it didn't work. Still says: #Object doesn't have an method called loadNewsFeed – Muqito Dec 10 '12 at 21:17
  • Oh, too many edits ;) - just move the handler-definition before setInterval then it works! – David Rettenbacher Dec 10 '12 at 21:28
  • Can you add a new answer?:o Because I don't really get it. :/ I want it to work like you wrote here: Now executes *immediately and registers* a handler. – Muqito Dec 10 '12 at 21:33
  • Hm... I just copied the code (and added `new News()`) and it works: http://jsfiddle.net/sfgVy/ – David Rettenbacher Dec 10 '12 at 21:42
  • I've learned my lesson. It was because I didn't declare the method BEFORE. I thought it didn't matter in this case so.. I thought of it as a regular "constructor" thing.. Sorry to bother. – Muqito Dec 10 '12 at 21:55