如何在Backbone.js视图中触发/绑定自定义事件?

时间:2021-07-18 23:54:59

I have a Backbone View that uses iScroll to implement a slideshow.

我有一个Backbone View,它使用iScroll来实现幻灯片放映。

iScroll publishes an onScrollEnd event, but I cannot seem to bind/subscribe to it inside the View:

iScroll发布了一个onScrollEnd事件,但我似乎无法在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);
    }

});

3 个解决方案

#1


24  

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事件绑定到视图的top元素;当视图的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()。

#2


25  

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.

它可能并不明显,但backbone.js视图中的事件属性仅用于DOM事件。自定义事件应该像James Brown上面提到的那样受到约束。

#3


18  

You should call the function directly or in your init, add this:

你应该直接或在你的init中调用该函数,添加:

self.bind('onScrollEnd', self.scrollEnd);

#1


24  

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事件绑定到视图的top元素;当视图的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()。

#2


25  

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.

它可能并不明显,但backbone.js视图中的事件属性仅用于DOM事件。自定义事件应该像James Brown上面提到的那样受到约束。

#3


18  

You should call the function directly or in your init, add this:

你应该直接或在你的init中调用该函数,添加:

self.bind('onScrollEnd', self.scrollEnd);