Hey,
I want to share some template that i usually use for starting new jQuery Plugin.
its base template that contains public methods, private methods, settings and custom events.
And here it come..
1 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 | /* (c) By Garry Lachman (http://www.garry-lachman.com), GPL License */ var PluginCustomEvents = { EVENT: "myPluginCustomEvent" }; (function($) { var plugin = this; $.fn.pluginTemplate = function(method) { var methods = { init : function(options) { this.pluginTemplate.settings = $.extend({}, this.pluginTemplate.defaults, options); return this.each(function() { var $self = $(this); var self = this; }); } }; var privateMethods = { privateMethod: function(){ } }; if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { console.error("No Method: " + method); } } $.fn.pluginTemplate.defaults = { defaultProperty: "defaultValue" }; $.fn.pluginTemplate.settings = {}; })(jQuery); |
Init plugin:
1 2 3 4 5 6 | $("#target").pluginTemplate(); // rename it to your plugin name // init with settings $("#target").pluginTemplate({ property1: "value" }); |
Call public methods:
1 | $("#target").pluginTemplate("method_name", "parameters"); |
Call private methods (inside the plugin):
1 | privateMethods.privateMethod.call(this, parameters ...); |
Have Fun ![]()
Garry Lachman







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