2

I have a decent understanding of the "this" keyword, but for some reason it's still tripping me up in this specific case. Inside the bindEvents method, when I'm binding the submit event to the form, it then executes fetchTweets. I understand that now that it's inside a callback function from the "on" method, so "this" now refers to the form that the event was bound to, rather than the parent object "Tweets".

My understanding was that it is common practice to declare self = this at the top of a method to cache the parent object to prevent later issues with a callback, but in this case it won't work because the sole purpose of that method is to be a callback function for the form submission event.

I know about .call and .apply and even $.proxy, I was just wondering if there was a need to use them in this case, or if I'm missing something obvious. I have this code working using $.proxy, I just thought there might be a smarter way of going about it.

var Tweets = {

    init: function ( config ) {
        var self = this;
        self.config = config;
        self.url = 'http://search.twitter.com/search.json?callback=?';
        self.bindEvents();
    },

    bindEvents: function() {
        var self = this;
        // bind events as needed
        self.config.form.on('submit', self.fetchTweets );
    },

    fetchTweets: function(e) {
        e.preventDefault();
        var self = this;
        var term = self.config.form.find('#term').val();

        // grab tweets from the server
        $.getJSON(self.url, { q: term }, function(data) {
            self.displayTweets(data);
        });
    },

    displayTweets: function(data) {
        var self = this;
        var tweetList = self.config.list;
        tweetList.empty();
        // append each tweet to the list
        $.each(data.results, function(index, tweet){
            $('<li></li>').text(tweet.text).appendTo(tweetList);
        });
    }
};

Tweets.init({
    form: $('#getTweets'),
    list: $('#tweets')
});

2 Answers 2

1

Instead of using self.<member>, try using Tweets.<member>. You can't do var self = this inside the method, because this is already something other than Tweets. But since you have a variable to refer to the object you're creating, you can just use that. :)

1
  • Thanks for the answer, that makes sense. Appreciate it!
    – rabhw
    Commented Mar 1, 2012 at 19:30
0

You could also wrap your event handler in an anonymous function as follows:

self.config.form.on('submit', function(e) { self.fetchTweets(e); });

Then don't do var self = this; in any method other than the method that binds the handlers. It's safe to use this.

1
  • Thanks for the answer and a different approach to the other answer. Much appreciated, it's clearer to me now.
    – rabhw
    Commented Mar 1, 2012 at 19:31

Not the answer you're looking for? Browse other questions tagged or ask your own question.