所以我有一个通过观察窗口上的滚动事件来实现固定标题的 View 。
didInsertElement: function () {
var self = this;
$(window).on("scroll resize", function () {
if (self.onWindowScroll) {
Ember.run.throttle(self, 'onWindowScroll', 150);
}
});
},
onWindowScroll: function () {
//do stuff
},
willDestroyElement: function () {
this.set('onWindowScroll', null);
}
这可行,但我想知道是否有更干净的方法来删除附加到滚动事件的逻辑。也许我们无能为力,因为它的事件本身就在窗口上,但只是请互联网专家分享一些智慧:)。
当 View 被清理时,摆脱 View 中定义的事件会很巧妙。另外,我没有取消绑定(bind)窗口本身的滚动事件,因为在窗口滚动时可能还有其他组件/ View 需要执行某些操作,而我不想干扰这些组件/ View 。
最佳答案
是的,您实际上并没有取消订阅该事件,您只是在调用该事件时忽略它。实际上取消订阅会更好。
didInsertElement: function () {
var self = this;
$(window).on("scroll resize", {scope:this}, this.onWindowScroll);
},
onWindowScroll: function (event) {
Ember.run.throttle(event.data.scope, 'onWindowScrollThrottle', 150);
},
onWindowScrollThrottle: function () {
//do stuff
},
willDestroyElement: function () {
$(window).off("scroll resize", this.onWindowScroll);
}
关于javascript - 一旦 View 被破坏,删除附加到窗口范围的事件的更干净的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24248977/