Preface

Multiple times in jQuery usual practice is to revaulate / reselect values every single time we manipulate them. Take an example

<div id =”#letsdoit”> <!—- SOMETHING HERE → </div>
and my function

var app = {
foo : $(‘#letsdoit’)};
This way we will not be referencing the div again but instead will be using app.foo with cleaner global space. Now suppose if i want to append some HTML as example in the above div

[sourcecode language=”javascript”]
var addHTMLCustom = function (text) {
var myText = $(‘<p></p>’).text(text);
app.foo.append(myText);
};

[/sourcecode]

above is perfectly fine as app.foo is valid jQuery object. Improving a bit this above function can be added in global namespace thus avoiding any code pollution.

[sourcecode language=”javascript”]
var app = {
foo : $(‘#letsdoit),
addHTMLCustom : function (text) {
var myText = $(‘<p></p>’).text(text);
app.foo.append(myText);
}
};
[/sourcecode]

All good, but there is a visibility problem -it seems that addHTMLCustom is part of global namespace but as we know it’s just our own for the specific div “#letsdoit”. It makes sense to have a function that acts on object to be within the scope of object alone.

[sourcecode language=”javascript”]</pre>
$.extend(app.foo, {
addHTMLCustom : function (text) {
var myText = $(‘<p></p>’).text(text);
this.append(myText);
}
});

[/sourcecode]

As you notice now its cleaner and easy to extend any functionality for any object without affecting the namespace.

Why to use EXTEND?

Clean & easy to add multiple functionalities

[sourcecode language=”javascript”]
$.extend(app.foo, {
add : function () {},
edit : function () {},
remove : function () {}
});
[/sourcecode]

OR for usual practice as passing second parameters in JSON manipulation we can think about

[sourcecode language=”javascript”]
var myHTMLFunctions = {
add : function () {},
edit : function () {},
remove : function () {}
};

$.extend(app.foo, myHTMLFunctions);

[/sourcecode]

Easier to work with multiple component sharing same functionality

(whats term in OOAD for that can you recall?)
A more convenient method would to cache a JSON object with the common functionalities, and use $.extend to slap those onto the relevant components,

[sourcecode language=”javascript”]
var myHTMLFunctions = {

add : function () {},

edit : function () {},

remove : function () {}

};

$.extend(app.foo, myHTMLFunctions);

$.extend(app.bar, myHTMLFunctions); // another div having same functionality
[/sourcecode]

We can also utilize Javascript prototyping at a lower level to achieve the

Ravi Tiwari

Geeky mind, nerdy heart, father of 2 and occasional day dreamer ;)

Want to work with us? We're hiring!