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
}
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With