How to trigger / bind custom events in Backbone.js views?

38,380

Solution 1

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().

Solution 2

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.

Solution 3

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

self.bind('onScrollEnd', self.scrollEnd);
Share:
38,380
meleyal
Author by

meleyal

Updated on July 19, 2020

Comments

  • meleyal
    meleyal almost 4 years

    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);
        }
    
    });
    
  • meleyal
    meleyal about 13 years
    I ended up just calling the function directly. Seems to defeat the point but it works :)
  • T. Junghans
    T. Junghans almost 12 years
    For me this answer was just as important as the accepted answer. Thanks.
  • VisioN
    VisioN over 9 years
    Or less verbose self.$el.trigger('onScrollEnd');.