Sorry for the long read, but it would be nice if you can share your thoughts anyway. :)
So.. the technique is described in Paul Irish's blogpost here - http://paulirish.com/2009/markup-based-unobtrusive-comprehensive-dom-ready-execution and then extended by Jason Garber here - http://viget.com/inspire/extending-paul-irishs-comprehensive-dom-ready-execution .
The main idea is to have a json object that would contain all of you code that is supposed to be executed when a particular page (controller and/or view) is loaded (on DOM-ready).
The object would look something like:
APP = {
controller1 : {
view10: function(){ ... },
view11: function(){ ... }
},
controller2: {
view20: function() {...},
view21: function() {...}
}
}
Then you change your <body>
into
<body data-controller="controller_name" data-action="view_name">
and then with some JS goodies when the DOM is ready there is an automatic call to APP.controller_name.view_name()
.
This is super awesome because you can put all of your to-be-executed-on-DOM-ready scripts on one place and these scripts are executed without additional code.
And now to the actual question: What to do with the other JS functions for a particular controller or view/page that are not supposed to be executed when the DOM is ready but when an event occur (e.g. onclick="someFunction()"?
It would be really nice if these functions are within the appropriate APP.controller_name
namespace because that would help maintain the code. And with that said, I'm currently changing my APP object into something like:
APP = {
controller1 : {
view10: function(){ ... },
view11: function(){ ... },
extraStuff10: function: () {...},
extraStuff11: function: () {...}
},
controller2: {
view20: function() {...},
view21: function() {...},
extraStuff20: function: () {...}
}
}
And this is all good - APP.controller1.view10()
is executed automatically and you can call APP.controller1.extraStuff10()
when you need it afterwards. But there one serious drawback for that structure - view10() and extraStuff10() have absolutely identical structure so you can't tell whether extraStuff10() is a function that is waiting to be executed when an event occur OR if there is an actual view/page that is called extraStuff and the content of that function will be executed when the page is loaded.
I'm thinking of changing the function view10() into an object that contains init() function (and we'll place the script-for-DOM-ready inside) like that:
APP = {
controller1 : {
view10: {
init(): function(){ ... }
},
extraFunction10: function: () {...}
}
}
This will give clear separation of the DOM-ready functions and the other functions but I'm wondering if that is the best way to accomplish that stuff... Any ideas?