I would like to do something like this.
var foo = function() {
this.run = function() {
alert('got');
}
this.init = function() {
this.run();
}
this.init();
};
window.onload = function() {
var f = new foo();
$(f).bind('run', function() { // this doesn't work
alert('ran!');
});
};
It doesn’t work though. How can I subscribe to a method of another object?
You cannot bind event handlers directly to functions – you bind them to events! You will need to trigger a custom event in run():
Now you’re able to subscribe to this event the way you already did:
This will work for events triggered after the handler has been bound, so the event triggered in the constructor will most likely not be caught.