【发布时间】:2015-02-02 13:57:14
【问题描述】:
我的 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);
【问题讨论】:
-
请注意,您可能不需要将 self 包装到 jQuery 对象中,所以不要使用
$(self).find,只需使用self.find -
整个设计看起来过于复杂。您可能应该简单地将上下文保持在闭包中,而不是在数据中设置函数。
-
dystroy 我认为我必须将函数放入数据中以便稍后从插件执行流程之外调用它们?
标签: javascript jquery plugins timeout