I’m relatively new to JavaScript and repeatedly find myself writing methods in a helper object which take in a callback as a parameter e.g.
var utilities = {
getTweets: function (user, maxTweets, callBack) {
var obj = $(this);
$.getJSON('http://api.twitter.com/1/statuses/user_timeline.json?callback=?&screen_name=' + user + "&count=" + maxTweets, function (data) {
callBack(data);
});
};
I then call it like so:
utilities.getTweets("TESTUSER", 4, function (tweets) {
.....
});
Given I am calling the code above using setInterval is this likely to leak over time/is there a better way to write this?
What you’re doing is mostly fine, except that there’s no need to create the extra closure. Passing a closure written like:
is just the same as passing
callBackdirectly in the parameter list.However if you can guarantee running with jQuery 1.5 or later, then a better method is to just have
getTweets()return the JQXHR object, and then you can use “deferred” methods in the client code:and then in the client code:
In this way you can completely decouple the callback from the implementation. Indeed you can register multiple callbacks, and error handlers, all without touching the implementation of
utilities.NB: use of a map for
dataabove also protects your code against parameter injection.