I’m writing a small CMS as a jQuery AJAX plugin and though it’s by no means excessively long (currently about 500 lines) I can see it would be nice to be able to split it into separate files, one for each “subclass”:
(function($) {
$.fn.myCMS = function() {
this.classOne = function() {
...
}
this.classTwo = function() {
...
}
}
})(jQuery);
In the example above, I would like to put the code for classOne in one file, classTwo in another and the myCMS “baseclass” in a third. Is it possible to achieve this with with something like this (in each of the “subclass” files)?
$.extend(myCMS,classOne = function() {
...
})
Many thanks,
JS
You want to add to the “plugin” with a private scope / separation of concern. This can be important for maintenance and long-term extensibility of your plugin-based web application, regardless of whether everything will be built into one file or multiple files.
You can create a private scope and extend an existing jQuery.fn method by attaching methods directly or by adding to the jQuery.fn.foo method’s prototype
You can use jQuery.extend(), which in this case is really a “shorthand” for adding a method to the constructor instance as the first method above. You have to encapsulate whatever you’re adding into an object (typically this would be an anonymous object):
From a design perspective if you have “classes” that need to get at the same closured variables frequently they should probably be part of the same function scope/closure, or you should expose getters and setters for those closured variables (perhaps with the _foo convention that shows they are intended to be used only by your code).
If you want to be a hacker and you need to get at closured variables from a different scope, I believe you can do so by executing these new methods with their own scope using .call() or .apply() from the other scope. I can try to whip up some samples of how this works, but it will be a good idea if you do your own research into how scope resolution works in these kinds of scenarios.
I believe you can “borrow” the scope from the original “plugin” method by using a with ($.fn.myCMS) { } construction but I am not 100% positive about that because I haven’t done it myself, only read about it.