我的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);
答案 0 :(得分:1)
将函数传递给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) );