The Code
/* * Concepts Demonstrated: * * + Namespacing * + Pluggable Architecture * + bind/trigger with custom events * * Assumes Familiarity with: * * + Function.prototype * + $.extend() */ /* The jQuery Extension Code */ if (!MyApp) var MyApp = {}; $.extend(MyApp, { target: null, events: { init : 'onInit', run : 'onRun', finish : 'onFinish' }, main: function(target) { var events = MyApp.events; var _self = [this]; this.init(target); $(MyApp).trigger(events.init, _self); this.run(); $(MyApp).trigger(events.run, _self); this.finish(); $(MyApp).trigger(events.finish, _self); } }); MyApp.main.prototype.init = function(target) { this.target = target; $(this.target).append('
MyApp.init Called
'); }; MyApp.main.prototype.run = function() { $(this.target).append('
MyApp.run Called
'); }; MyApp.main.prototype.finish = function() { $(this.target).append('
MyApp.finish Called
'); }; /* Add the extension to jQuery */ $.fn.myapp = function() { return this.each(function() { new MyApp.main($(this)); }); }; /* The Plugin code */ var MyPlugin = function(app) { $.extend(app, { MyPlugin: this.init(app) }); }; MyPlugin.prototype.init = function(app) { this.parent = app; $(this.parent.target).append('
MyPlugin fired
'); }; $(MyApp).bind('onRun', function(e, app) { new MyPlugin(app); });