Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
    }

});
like image 209
meleyal Avatar asked Mar 21 '11 14:03

meleyal


People also ask

How do I trigger an event in Backbone JS?

js trigger Event is used to invoke or callback the function for the given event or a space-delimited list of events. The subsequent arguments will be passed along to the event callbacks in order to trigger it. Parameter Values: event: It is used to bind an object with an event.

How does backbone js work?

Backbone. js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.

Why use backbone js?

BackboneJS allows developing of applications and the frontend in a much easier way by using JavaScript functions. BackboneJS provides various building blocks such as models, views, events, routers and collections for assembling the client side web applications.

What are views in Backbone JS?

The Backbone. js Views specify how your data looks like. They represent model's data to the users. They can be used with any JavaScript template library.


Video Answer


3 Answers

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.

like image 76
Dmitry G. Avatar answered Oct 02 '22 10:10

Dmitry G.


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

like image 23
Bart Avatar answered Oct 02 '22 09:10

Bart


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

self.bind('onScrollEnd', self.scrollEnd);
like image 43
James Brown Avatar answered Oct 02 '22 09:10

James Brown