There is few ways to create javascript object and use its as class.
In this artical i will you my favorite way to implement javascript classes.
I will combaine jQuery in this example.
First of all lets create basic object:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| var GarryObj = {
init: function(options, target) {
this.options = $.extends({}, this.options, options);
this.$target = $(target);
this._draw();
},
options: {
width: 100,
height: 100,
},
_draw: function() {
this.$target.css({width: this.options.width,
height: this.options.height});
}
} |
We create here basic class that have 2 functions and one object to store the options.
the init class gets user options and the target (like html div).
then we merge the default options with the user options using jQuery extends function and
store the target as jQuery instance as $target.
The _draw function manipulate the target – here we build the ui by user options.
To create an instance of the class we need to add some code to the (i use to put it on js heaer file).
1 2 3 4 5 6 7
| if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
} |
Now lets create a instance of our class:
We need to add target div:
and than
1 2
| var garryTest = Object.create(GarryObj);
garryTest.init({width: 150, height: 150}, $("#test_div")); |
Have fun 
Garry Lachman
Share on Facebook
jQuery Communicator Singleton (Manage & Cache ajax requests)
Hey,
I wrote this class for cache ajax request if the same request sent twice.
The second reason why i use this class is a like there is only one exit point
from the application.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
var instantiated;
var retry = new Array();
var cached_data = new Array();
function init (){
return {
dispatch:function(url, callback){
var self = this;
if (Communicator.getInstance().cached_data[url]) {
callback(Communicator.getInstance().cached_data[url]);
return;
}
if (!retry[url]) {
retry[url] = 0;
}
var _rq = $.ajax({
url: url,
timeout: 30000,
success: function(_data){
Communicator.getInstance().cached_data[url] = _data;
callback(_data);
},
error: function(){
if (retry[url] < 3) {
retry[url]++;
dispatch(url, callback, retry[url]);
} else {
callback("");
}
}
});
},
cached_data: {}
}
}
return {
getInstance :function(){
if (!instantiated){
instantiated = init();
}
return instantiated;
}
}
})()
Using the class
2
3
4
5
6
7
8
9
10
11
12
var error = false;
try {
data = eval("("+data+")");
} catch(err) {
error = true;
}
if (!error) {
console.log(data);
}
});
Have fun
Garry