Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone event trigger

I want to trigger a custom event from my backbone view class then where I Instantiate the view I want to listen for the event.

Simplified Example:

var view = Backbone.View.extend({
     render:function(){
         this.trigger('customEvent', "working");
     }
});

// Separate js file with jquery ready method.

$(function() {
    var myView = new view();
    myView.bind('customEvent', this.customEventHandler);

    function customEventHandler() {
        // do stuff
    }
});
like image 376
Chapsterj Avatar asked May 14 '26 12:05

Chapsterj


1 Answers

If the error you're getting is "callback[0] is undefined", then your problem is in the event binding. Where you have:

myView.bind('customEvent', this.customEventHandler);

What does this refer to, and does it have a customEventHandler method? If this is all happening in the global scope, you can just pass in a plain function, no this required:

var view = Backbone.View.extend({
     render:function(){
      _this.trigger('customEvent', "working");
     }
});

// define your callback
function customEventHandler() {
    // do stuff
}

myView = new view();
myView.bind('customEvent', customEventHandler);

This will work even with a $(document).ready() function.

like image 140
nrabinowitz Avatar answered May 17 '26 01:05

nrabinowitz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!