Javascript 如何在 Backbone.js 视图中触发/绑定自定义事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5379290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to trigger / bind custom events in Backbone.js views?
提问by meleyal
I have a Backbone View that uses iScrollto implement a slideshow.
我有一个使用iScroll实现幻灯片放映的 Backbone 视图。
iScroll publishes an onScrollEnd
event, but I cannot seem to bind/subscribe to it inside the View:
iScroll 发布了一个onScrollEnd
事件,但我似乎无法在视图中绑定/订阅它:
App.Views.Scroller = Backbone.View.extend({
events: {
'onScrollEnd' : 'scrollEnd'
},
initialize: function(){
var self = this;
this.scroller = new iScroll('content-scroller', {
onScrollEnd: function() {
self.trigger('onScrollEnd');
}
});
},
scrollEnd: function(e){
// never called :(
console.log(e);
}
});
采纳答案by Bart
Your onScrollEnd event is bound to the view's top element; scrollEnd will be called when the view's HTML element received an onScrollEnd event.
您的 onScrollEnd 事件绑定到视图的顶部元素;当视图的 HTML 元素收到 onScrollEnd 事件时,将调用 scrollEnd。
But you are triggering an onScrollend event on your View object, not the element.
但是您正在 View 对象上触发 onScrollend 事件,而不是元素。
So you probably want to say $(self.el).trigger('onScrollEnd');
instead, or perhaps call the function directly: self.scrollEnd()
.
所以你可能想说$(self.el).trigger('onScrollEnd');
,或者直接调用函数:self.scrollEnd()
。
回答by Dmitry G.
It might not be obvious, but event
property in backbone.js views is used only for DOM events. Custom events should be bound as James Brown mentioned above.
这可能不是很明显,但是event
backbone.js 视图中的属性仅用于DOM 事件。自定义事件应该像上面提到的 James Brown那样绑定。
回答by James Brown
You should call the function directly or in your init, add this:
您应该直接调用该函数或在您的 init 中添加以下内容:
self.bind('onScrollEnd', self.scrollEnd);