【问题标题】:Ember.js 1.2.0 debounce not working as expected on jquery eventsEmber.js 1.2.0 debounce 在 jquery 事件上没有按预期工作
【发布时间】:2014-01-02 00:49:50
【问题描述】:

我正在尝试在窗口的调整大小事件上设置去抖动,并且以前能够使用下划线和 jquery 如下:

$(window).on('resize', _.debounce($.proxy(this.windowWidthChanged, this), 333));

我带着这个想法并尝试将其应用到 Ember 的Ember.run.debounce 如下:

$(window).on('resize', Ember.run.debounce(this, this.windowWidthChanged, 333));

事件监听器似乎根本没有触发......

【问题讨论】:

    标签: jquery ember.js debouncing


    【解决方案1】:

    正如您可能已经猜到的那样,您没有将函数传递给 resize 事件,而是传递取消信息(调用 debounce 的结果)。

    var self = this;
    $(window).on('resize', function(){ Ember.run.debounce(self, self.windowWidthChanged, 333)});
    

    这又回到了经典的 setTimeout 困境,为什么它会立即运行?

    setTimeout(alert('hello'),2000)
    

    【讨论】:

    • 谢谢 - 任何阅读此内容以供将来参考的人,从 ember 1.4 开始,您可以使用 Ember.run.bind,其作用类似于 $.proxy
    【解决方案2】:

    我最终将它包装在代理内的匿名函数中以维护 this 上下文:

    $(window).on('resize', $.proxy(function() {
        Ember.run.debounce(this, this.windowWidthChanged, 333);
    }, this));
    

    我想你也可以将Ember.run.debounce 移动到windowWidthChanged 中。

    【讨论】:

      猜你喜欢
      • 2014-03-27
      • 2018-03-17
      • 2019-07-13
      • 2012-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多