我在我的jQuery插件中有一些行为附加到keyup事件。一切正常,除了应该在立即执行超时后触发的函数。
//attach keyup event for the searchbox
self.data('gallery_searchTimeout',null); //to enable a delay on the keypress search event
$(self).find('.gallery-search').keyup(function(){
var needle = 'look for me';
var delay = 2000;
//if a timer is already set, clear it in favor of our new timer
if (self.data('gallery_searchTimeout') != undefined) clearTimeout(self.data('gallery_searchTimeout'));
self.data('gallery_searchTimeout', setTimeout((self.data('search')(self,needle)), delay) );
});
var search = function(self,needle) {
console.log('search called with needle: '+needle);
};
self.data('search',search);
将函数传递给setTimeout
而不是调用它。
改变
self.data('gallery_searchTimeout', setTimeout((self.data('search')(self,needle)), delay) );
自
self.data('gallery_searchTimeout', setTimeout(self.data('search').bind(null,self,needle), delay) );
或
self.data('gallery_searchTimeout', setTimeout(function(){
self.data('search')(self,needle);
}, delay) );