我对“this”关键字有一个体面的理解,但由于某种原因,它仍然让我在这个特定的情况下绊倒。在bindEvents方法内部,当我将提交事件绑定到表单时,它会执行fetchTweets。我明白现在它已经在“on”方法的回调函数中,因此“this”现在指的是事件绑定的表单,而不是父对象“Tweets”。“this”关键字在javascript回调函数中
我的理解是,通常的做法是在方法的顶部声明self = this以缓存父对象,以防止稍后发生回调问题,但在这种情况下,它不起作用,因为唯一目的是该方法将成为表单提交事件的回调函数。
我知道.call和.apply,甚至$ .proxy,我只是想知道在这种情况下是否需要使用它们,或者如果我错过了明显的东西。我有这个代码使用$ .proxy工作,我只是认为可能有一个更智能的方法去实现它。
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')
});
感谢您的回答,这是有道理的。欣赏它! – rabhw 2012-03-01 19:30:49