【问题标题】:setTimeout not working inside jQuery pluginsetTimeout 在 jQuery 插件中不起作用
【发布时间】: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


【解决方案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) );

【讨论】:

  • 我喜欢最后一个建议,效果很好。谢谢。
猜你喜欢
  • 2012-05-06
  • 2019-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多