Delegating events for objects; How to listen to events?
How can I listen for custom events in a javascript object? I'm trying to have a method on the object of the object fire the object when the event is fired, but unlike DOM
elements, I cannot register a listener for the object.
How can I structure my application to listen for fired events and then take an action?
JS:
$(document).ready(function(){
var app = {};
app.doStuff = function(){ alert("Yo!");};
$(app).on("myCustomEvent", function(){
alert("doing stuff");
app.doStuff();
});
$("body").on('click', "#trigger", function(){
alert("triggered");
$(this).trigger("myCustomEvent");
});
});
submitted at jsbin: http://jsbin.com/zopubuso/1/edit
The reason of that:
I am creating a basic application where I have a global event event inside my object app
. I am trying to communicate between views by firing events:
t.
app.on("myEvent", MyView.model.doStuff);
app.trigger("myEvent");
But I cannot activate events.
source to share
try:
trigger with jquery:
$(app).trigger("myCustomEvent");
trigger as base event:
first you will need to expand the object with Backbone.Events
:
var app = {};
_.extend(app, Backbone.Events); // underscore.js '_.extend', We can also use jquery '$.extend()'
... on("myCustomEvent")...
app.trigger("myCustomEvent");
demo: http://jsfiddle.net/A5484/1/
Update from agconti.
Here's a simple way to bind events on the backbone:
var app = _.extend({}, Backbone.Events);
var myView = Backbone.View.extend({
initialize: function(){
... other configuration stuff ...
app.on( "myCustomEvent", function(){
this.doStuff();
}, myView);
},
doStuff: function(){ alert("Yo!"); }
});
app.trigger('myCustomEvent');
*
it is much more beneficial to use the base event object and then add the listener with the help app.on();
as I tried to do.
source to share