Posts Tagged ‘prototype’

script.aculo.us provides JS libraries for animation, drag and drop, Ajax controls, DOM utilities, and unit testing. Good to know.

http://script.aculo.us/

Advertisements
String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) {
        return typeof (args[number] != 'undefined') ? args[number] : '{' + number + '}';
    });
};
Extending javascript global object is not a good idea. This can be defined as a utility funciton with in your application's global js object/file.

Extending  Reference - http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format

Very good links to understand OOP using Javascript prototype …

http://mckoss.com/jscript/object.htm

http://www.klauskomenda.com/code/javascript-inheritance-by-example/

http://www.crockford.com/javascript/inheritance.html

Javascript – Prototype Object

Posted: November 22, 2010 in Javascript
Tags: ,

If u’re interested in extending JavaScript and creating your own objects and libraries, the prototype object is a must learn topic.

Like the the pre-built ones, such as document or Math, Custom objects allow us to build up our own personal JavaScript “toolbox” that extends beyond what the pre-build objects have to offer.

The prototype object of JavaScript, introduced starting in JavaScript 1.1, is a prebuilt object that simplifies the process of adding custom properties/ methods to all instances of an object. In JavaScript, we’re allowed to add custom properties to both prebuilt and custom objects.

Ex:

<script type=”text/javascript”>
function computearea() {
var area = this.radius * this;
.radius * 3.14;
return area;
}
function computediameter() {
var diameter = this;
.radius * 2;
return diameter;

}
function circle(r) {
//property that stores the radius
this.radius = r;
this.area = computearea;
this.diameter = computediameter;
}

var mycircle = new circle(20);
//alerts 1256
alert(“area=”+ mycircle.area());
//alerts 400
alert(“diameter=”+ mycircle.diameter());

</script>
A custom property added this way only exists for that instance of the object. If I were to spit out another instance of circle(), called “bigcircle”, for example, bigcircle.radius would by default return “undefined” until I go over the process again of first defining bigcircle.radius, as with mycircle.

When you just wished all instances of the object would recognize the custom property, that’s where the prototype object of JavaScript comes in.

Let’s define the custom property “pi” in the above in a way so it’s a default property of all instances of circle():

//First, create the custom object “circle”
function circle(){}
circle.prototype.pi=3.14159;
// create the object method
function alertmessage(){
alert(this.pi);
}

circle.prototype.alertpi=alertmessage;

While you are free to use the prototype object on any custom objects, this is NOT the case with prebuilt ones (such as image, string etc). JavaScript only allows you to “prototype” prebuilt objects that are created with the new keyword, such as the following:

  • The image object
  • The string object
  • The date object
  • The Array object

Let’s see an interesting example on how to extend the prebuilt String object of JavaScript to include a method that writes any string backwards when called upon

<script type=”text/javascript”>
/*code for extending String object with method that writes text backwards*/
//core custom method for writing text backwards
function outputbackwards(){

for (i=this.length-1;i&gt;=0;i–)
document.write(this.charAt(i));
}

//Attach custom method to string object
String.prototype.writeback=outputbackwards;
var message1=”Welcome to my site!”;
message1.writeback();
var message2=”Today is a beautiful day”;
message2.writeback();

</script>

call() vs apply()

JavaScript 1.3 includes two new methods for the Function object, call() and apply(). The apply() method is a variation on the call() method. The apply() method lets you pass the parameters from one method to the other in a different way than the call() method does it.

The call() method requires the full list of parameters, as shown in the previous page: exterior.call(this, extColor, doorCount, airWing, tireWidth);

The apply() method, on the other hand, lets you specify arguments on its second parameter: exterior.apply(this, arguments);

References

The prototype object of JavaScript – http://www.javascriptkit.com/javatutors/proto.shtml
JavaScript closures – http://www.mennovanslooten.nl/blog/post/62
JavaScript 1.3 Overview, Part I – http://www.webreference.com/js/column25/index.html
JavaScript 1.3 Overview, Part II – http://www.webreference.com/js/column26/index.html
Object Oriented Programming in JavaScript – http://mckoss.com/jscript/object.htm

AJAX Sample

Posted: November 22, 2010 in Uncategorized
Tags: , , , ,
1. JQuery – AJAX
 
jQuery.ajaxSetup( options ) – A set of key/value pairs that configure the default Ajax request. All options are optional.

Ex:
$.ajaxSetup({
url: “/xmlhttp/”,
global: false,
type: “POST”,
data: myData
});

Sets the defaults for Ajax requests to the url “/xmlhttp/”, disables global handlers and uses POST instead of GET. The above Ajax request then sends some data without having to set anything else.

Note: Global callback functions should be set with their respective global Ajax event handler methods-.ajaxStart(), .ajaxStop(), .ajaxComplete(), .ajaxError(), .ajaxSuccess(), .ajaxSend()-rather than within the settings object for $.ajaxSetup().

Show a loading message before AJAX request starts

Ex:
$(“#loading”).ajaxStart(function(){
$(this).text(‘Triggered ajaxStart handler.’);
//$(this).show();
});

2. Microsoft AJAX Toolkit Sample
 
<div id=”OverlayContent”>
Content will be shown here!
</div>

<div class=”data”>
<div class=”bums clearfix”>
<div class=”bum”>
<a href=”#” class=”bumoverlay” data-bumid=”556119″>
<img src=”default_large.jpg”/>
</a>
</div>
<div class=”bum”>
<a href=”#” class=”bumoverlay” data-bumid=”556119″>
<img src=”default_large.jpg”/>
</a>
</div>
</div>
<div class=”lists clearfix”>
<div class=”list”>
<a href=”#” class=”listoverlay” data-listid=”2″ data-uid=”10″>
<img src=”med_9745314cb3f92d6460abfdb895c865d0.jpg”/>
</a>
</div>
<div class=”list”>
<a href=”#” class=”listoverlay” data-listid=”3″ data-uid=”10″>
<img src=”med_9745314cb3f92d6460abfdb895c865d0.jpg”/>
</a>
</div>
</div>
</div>

<script>
var OverlayControl = function() { }

OverlayControl.prototype = {
Key : ‘MediaContent’,
ShowbumOverlay : function(e, element) {
var aid = element.getAttributeNode(‘data-bumid’).value;
var r = new Sys.Net.WebRequest();
r.set_url(‘/Modules/abc.asmx/GetData?’);
r.set_body(String.format(‘contentkey={0}&queryparams={1}’, e.Key, ‘bum;’ + aid));
r.set_httpVerb(‘POST’);
r.set_userContext(this);
r.add_completed(e.ResponseHandler);
r.invoke();
},
ShowlistOverlay : function(e, element) {
//alert(this.childNodes[0].getAttributeNode(‘data-uid’).value);
var listid = element.getAttributeNode(‘data-listid’).value;
var uid = element.getAttributeNode(‘data-uid’).value;
var r = new Sys.Net.WebRequest();
r.set_url(‘/Modules/abc.asmx/GetData?’);
r.set_body(String.format(‘contentkey={0}&queryparams={1}’, e.Key, ‘list;’ + listid + “;” + uid));
r.set_httpVerb(‘POST’);
r.set_userContext(this);
r.add_completed(e.ResponseHandler);
r.invoke();
},
HideOverlay : function(e, element) {
var target = $(‘#OverlayContent’);
target[0].innerHTML = “Content will be shown here!”;
},
ResponseHandler: function(executer, args) {
var ele = executer.get_webRequest().get_userContext();
//try
//{
if (executer.get_responseAvailable())
{
var result = executer.get_xml();
var target = $(‘#OverlayContent’);
if (document.all)
target[0].innerHTML = result.documentElement.firstChild.text;
else // Firefox  
target[0].innerHTML = result.documentElement.firstChild.textContent;
}
//}
//finally {
// userContext._requestingData = false;
//}
}
};

var overlayCtrl = new OverlayControl();

// Attach event (mouseover, mouseout) & event handler to every bum <a> tag
var bums = $(‘.bumoverlay’);
for(i=0;i <>
var currentbum = bums[i];
$addHandler(currentbum , “mouseover”,
// javascript closures implementation in for-loops – http://www.mennovanslooten.nl/blog/post/62
function(overlayCtrl, currentbum ) {
return function() {
overlayCtrl.ShowbumOverlay.apply(currentbum , [overlayCtrl, currentbum ]);
}
}(overlayCtrl, currentbum )
);
$addHandler(currentbum , “mouseout”,
function(overlayCtrl, currentbum ) {
return function() {
overlayCtrl.HideOverlay.apply(currentbum , [overlayCtrl, currentbum ]);
}
}(overlayCtrl, currentbum )
);
}

// Attach event (mouseover, mouseout) & event handler to every list <a> tag
var lists = $(‘.listoverlay’);
for(i=0;i <>
var currentlist = lists[i];
$addHandler(currentlist, “mouseover”,
function(overlayCtrl, currentlist) {
return function() {
overlayCtrl.ShowlistOverlay.apply(currentlist, [overlayCtrl, currentlist]);
}
}(overlayCtrl, currentlist)
);
$addHandler(currentlist, “mouseout”,
function(overlayCtrl, currentlist) {
return function() {
overlayCtrl.HideOverlay.apply(currentlist, [overlayCtrl, currentlist]);
}
}(overlayCtrl, currentlist)
);
}
</script>

//Note – You can directly test this post by copying everything 2 a .js file and refer it in .htm page

// function in JS are objects linked to function.prototype which itself linked 2 Object.prototype
// Every fn is created with 2 additioinal hidden properties – fn’s context, code that implements the fn’s behavior
// Function literal
var add = function (a, b) {
return a + b;
};

// Along with declared parameters fns receive 2 more parameters as arguments – this & arguments
// You can excess or less arguments while calling function than the defined arguments, you can use arguments to get all parameters in case of less
// parameters it will give undefined when accessing the non passed parameters
// function if it does not return anything then it will return “this”

var sum = function () {
var sum = 0; // name does not interfere with the variable defined outside
for (i = 0; i < arguments.length; i++) // arguments is not an array but is array like obj, it has length property but it lacks all other array methods
sum += arguments[i];
return sum;
}

document.writeln(sum(2, 3, 4, 6, 7, 8) + “<br/>”);

// 4 patterns function invocation
// 1. Method invocation pattern
var myObject = {
value : 0,
increment : function (inc) {
this.value += typeof inc === ‘number’ ? inc : 1;
}
};

myObject.increment();
document.writeln(myObject.value + “<br/>”);

myObject.increment(2);
document.writeln(myObject.value + “<br/>”);

// 2. Function invocation pattern – when a fn is not the property of an object
var newsum = add(3, 4);

// This kind of function is bound 2 global obj (mistake in design of lang)
// due to this mistake “this” can not be used in the inner function to access stuff of the employed function
// workaround is assign this to a variable in the main function

// Augment myObject with a double method
myObject.double = function () {
var that = this;
var helper = function () {
that.value = add(that.value, that.value);
}
helper();
};

myObject.double();
document.writeln(myObject.value + “<br/>”);

// 3. Construction invocation – by creating constructor fn (fns that are intended 2 be used with the new prefix are called constructors)
// JS is a prototypal inheritance lang i.e. objs can inherit properites directly from other objects which makes js as class-free
// If a fn is invoked with the new prefix then a new object will be created with a hidden link to the value of the fn’s prototype member
// & this will be bound 2 that new obj

//  By convention use capital start letter for variable
var Quo = function (string) {
this.status = string;
}

Quo.prototype.get_Status = function () {
return this.status;
};

var myQuo = new Quo(“confused”);

document.writeln(myQuo.get_Status() + “<br/>”);

// 4. Apply invocation pattern
// bcos js is a functional oo lang, fns can methods

// Apply lets us construct an array of arguments 2 use 2 invoke a fn. Apply takes 2 arguments, first one we can specify value for “this”, second is array of params

var array = [3, 4];

document.writeln(add.apply(null, array) + “<br/>”);

var newStatusObj = {
status : “called thru apply”
};

// newStatusObj does not inherit from Quo.prototype but we can invoke get_status method on newStatusObj eventhough it does not have it
document.writeln(Quo.prototype.get_Status.apply(newStatusObj) + “<br/>”);

// Exception handling – throw {}, try {}catch(e) {}

var newadd = function (a, b) {
if (typeof a !== ‘number’ || typeof b !== ‘number’)
throw { name: ‘TypeError’, message: ‘pass numbers’ };
return a + b;
};

var try_it = function () {
try {
newadd(‘fool it’);
} catch (e) { document.writeln(e.name + “: ” + e.message + “<br/>”); }
};

try_it();