patternjavascriptMinor
A simple javascript plugin architecture
Viewed 0 times
javascriptpluginsimplearchitecture
Problem
I've implemented the following code which allows me to bolt modules of code on to my core library via the prototype chain. It's quite prescriptive so any user creating a module has to create an init method and also has to define a queue method:
(working fiddle: http://jsfiddle.net/wG9Pv/)
Now this all works well but is this a good way of achieving it?
(working fiddle: http://jsfiddle.net/wG9Pv/)
//Constructor
test = function() {
this.tester = 'The instance was successfully created';
};
//A core method
test.prototype.amethod = function() {
};
//Extend method which facilitates the module system
test.extend = function(name,plugin) {
test.prototype[name] = plugin.init;
//later do something with the queue method that's been fed in via the 'plugin' object
};
//Add a module
test.extend('method1', {
init: function(val) {
console.log(this.tester);
},
queue: function() {
},
render: function() {
}
});
//add another module
test.extend('method2',{
init: function() {
console.log('Init of the plugin has been fired');
},
draw : function() {}
});
var test = new test();
test.method1('boom!');
test.method2();Now this all works well but is this a good way of achieving it?
Solution
Looks fine to me,
I would consider making extend a property of prototype though.
For nitpickings, I think
is preferred to
This ways developers will know to use
Please read Learning JavaScript Design Patterns for the cons of using the
You probably want to store the entire plugin object provided to
You probably want to throw an exception if the
I am not sure if you realize that
I would consider making extend a property of prototype though.
For nitpickings, I think
function Test() {
this.tester = 'The instance was successfully created';
};is preferred to
test = function() {
this.tester = 'The instance was successfully created';
};This ways developers will know to use
new when using test.Please read Learning JavaScript Design Patterns for the cons of using the
new keyword.You probably want to store the entire plugin object provided to
extend, not just keep init.You probably want to throw an exception if the
plugin does not have an init property.I am not sure if you realize that
method1 and method2 are at the end of the script also "core methods"?Code Snippets
function Test() {
this.tester = 'The instance was successfully created';
};test = function() {
this.tester = 'The instance was successfully created';
};Context
StackExchange Code Review Q#35367, answer score: 2
Revisions (0)
No revisions yet.