I am triggering a custom event, but can't find a way to bind an action to it from another file. I guess it is a scope issue but I just can't resolve it alone.
In my app entry file, I am triggering a custom boom
event like this :
var page_object_test = {};
_.extend(page_object_test, Parse.Events);
page_object_test.trigger("boom");
This piece of code is contained within a jQuery $(document).ready()
statement.
And then, from within a jQuery plugin heald in a different file, and enclosed within a (function($) {})(jQuery);
construct, I want to bind some function to my boom
event, but nothing happens :
var page_object = {
update_page_title : function(route, params) {
var new_title = "";
switch(route) {
default:
new_title = "La meilleure façon d'emmener vos enfants à l'école";
}
document.title.html(new_title);
}
};
_.extend(page_object, Parse.Events);
page_object.on("boom", function() {console.log(".on() binding is working!")});
Why can't I receive this event from another file? I realize I don't get how do Backbone events bubble up. More than the right way to write this, i would really love to be pointed out toward a clear explanation of the scope of those events.
Any explanation is most welcome
Your have a scope problem: page_object_test
must be know in the other file you want it to listen.
With backbone events, there is no such thing as event bubbling. It the variable itself that contains the info to make it react to .on('boom', function(){});
Four solutions:
1 - Global variable:
// File1
window.page_object_test = {};
_.extend(window.page_object_test, Parse.Events);
window.page_object_test.trigger("boom");
// File2
window.page_object_test.on('boom', callback); // Always prefer `on` over `bind`, depreciated in most frameworks
Global variables are said to be dangerous, but are the only way to communicate in the global scope. They need to be manipulated cautiously.
Ex: having 1 global object that stores the whole app state:
var window.AppState = window.AppState || {};
window.AppState.page_object_test = {}; // etc.
2 - DOM Element:
// File1
$('document').trigger('boom'); // or whichever jQuery selector
// File2
$('document').on('boom', callback);
This makes more sense if your event is actually related to a DOM element. This is often the case, but not always.
3 - Passing as argument
// File2
var generate_listener = function(page_object_test, callback) {
page_object_test = {};
_.extend(page_object_test, Parse.Events);
page_object_test.on('boom', callback);
return page_object_test;
}
// File1
var page_object_test = {};
page_object_test = generate_listener(page_object_test, function(){
// Do whatever you want here
});
page_object_test.trigger("boom");
This moves the issue to communicating generate_listener
instead so not much has been won.
Finally, take a look at AMD which was designed to modularize your app as you could expect (basically, it handles the global variable thing for you, making sure you don't use it in wrong situations).