Mar 28 2009
Flexible function call in JavaScript
If you have used popular JavaScript libraries like PrototypeJS, jQuery and so on (I have used only PrototypeJS and Adobe Spry), you may have noticed the flexibility of calling their API class and methods. Something like this while using PrototyeJS AJAX API:
new Ajax.Request(url, {
onSuccess: function(response) {
//do something
}
onException: function(response, exception) {
//do something
}
onFailure: function() {
//do something
}
});
I have figured out that creating a method that can handle such call is certainly not so hard and in my opinion, it does provide some level of flexibility in the code.
Here is the same code:
function clickIt(options) {
this.message = "";
this.afterClick = function() {};
for (var key in options) {
this[key] = options[key];
}
this._execute = function() {
alert(this.message);
this.afterClick();
}
this._execute();
}
The above method accepts a single object as an argument with two properties: message and afterClick and this._execute() is a kinda private method (JavaScript does not have an explicit access modifier). Now to call the above function:
Event.observe(window, 'load', function() {
$('iclick').observe('click', function(e) {
Event.stop(e);
new clickIt({
message: "This is some message",
afterClick: function() {
if (confirm("Are you sure")) {
window.location.replace(this.href);
}
}
});
});
});
Since {} is regarded as object in JavaScript so one can use it to make a function/class more flexible and extensible. But since, users calling this class will have no knowledge what arguments are acceptable so, documentation plays crucial role (If you are creating an API then, the success and usability of that API heavily depends on the quality of documentation that acts as valid contract between interface and implementation code).

-
anzaan
-
Prajwal Tuladhar


