čtvrtek 5. dubna 2012

Extending dojo standard modules

New dojo 1.7 is awesome. I really enjoy working with it. The new AMD modules let you do things easy and straightforward in javascript.


When you will developing some webapp, you will come across the situation when you will need to extend some dojo basic functionality.  For example I needed function for removing items from array at one particular index.


My first attempt was pretty straightforward and dumb.  I created new function in the module where I needed it:


define([
"dojo/_base/lang",
"dojo/_base/array",
...
], function(lang, array, ...) {

function removeFromArray(array, index) {
/* implementation */
}

/* rest of the module */

});

Few moment later, I needed same function in another module. Copy/paste is not a good idea, not even saying, that it is not good to have this kind of function in absolutely unrelated module. The solution is pretty elegant and easy. I just created a new module "my/extendedArray" that looked like this:


define([
"dojo/_base/lang",
"dojo/_base/array",
], function(lang, array) {

lang.mixin(array, {
remove: function (arr, indexToRemove) {
/* implementation */
}
});

return array;
});

Now, whenewer I need these extensions, I just switch "dojo/array" for "my/extendedArray" in the define or require. Anything else from "dojo/_base/array" works normally and I have available my own extensions in array module!

Of course, you can extend anything in dojo by this way. You just have to pick right extension mechanism - mixin, extend, or classy inheritance :-)



Žádné komentáře:

Okomentovat