如何在 Backbone.js 视图中触发/绑定自定义事件?
我有一个主干视图,它使用 iScroll 来实现幻灯片放映。
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);
}
});
I have a Backbone View that uses iScroll to implement a slideshow.
iScroll publishes an onScrollEnd
event, but I cannot seem to bind/subscribe to it inside the View:
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);
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这可能并不明显,但backbone.js 视图中的
event
属性仅用于 DOM 事件。自定义事件应绑定为 詹姆斯·布朗上面提到过。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.您的 onScrollEnd 事件绑定到视图的顶部元素;当视图的 HTML 元素收到 onScrollEnd 事件时,将调用scrollEnd。
但是您正在 View 对象上触发 onScrollend 事件,而不是元素上。
因此,您可能想改为使用
$(self.el).trigger('onScrollEnd');
,或者直接调用该函数:self.scrollEnd()
。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.
But you are triggering an onScrollend event on your View object, not the element.
So you probably want to say
$(self.el).trigger('onScrollEnd');
instead, or perhaps call the function directly:self.scrollEnd()
.您应该直接调用该函数或在 init 中添加以下内容:
You should call the function directly or in your init, add this: