Related
I have some JavaScript functions in each page that I call them after jQuery is loaded.
The function in Questions.aspx page is afterQuestions(), the function in Default.aspx is afterDefault() and so on ....
In my master page I am calling them like:
if(typeof(afterQuestion) == 'function') afterQuestions();
if(typeof(afterDefault) == 'function') afterDefault();
As the number of functions grew, I tried something like:
var _fs = [After, AfterDefault, afterSettings, afterQuestions];
for (var i = 0; i < _fs.length; i++) if (typeof (_fs[i]) == "function") _fs[i]();
But it doesn't work this way. Can you please help me how can I create an Array of functions and call them?
Edit: I think nobody had read the question well to see that the all functions won't exist at the same time and that was the problem creating the array. I solved it by adding created functions to a global array and the looping and excuting functions in that array
If the function is not defined, you will get a JavaScript error since you are trying to reference a variable that is not defined. The type of check in your original code gets around that issue.
Your best bet is to namespace the functions into an object and use dot notation.
var methods = {
After : function () {console.log("After"); },
AfterDefault : function () {console.log("AfterDefault"); },
afterSettings : function () {console.log("afterSettings"); }
};
var _fs = [methods.After, methods.AfterDefault, methods.afterSettings, methods.afterQuestions];
for (var i = 0; i < _fs.length; i++) {
if (typeof (_fs[i]) == "function") {
_fs[i]();
}
}
Now when you want to register the methods you can just add to the methods object.
methods = methods || {};
methods.afterSettings = function () { console.log("added this in"); };
Now if the method is not defined the namespace will return undefined and the check will not error out.
I want to enforce a miterLimit in actual pixels rather than as a ratio of the lineWidth. To do this, I'd like to hook any changes to lineWidth, and set the miterLimit simultaneously and automatically. I've used custom setters on objects before, but if I replace the lineWidth setter, I don't know of any way to actually pass the value to set on through to the actual canvas context.
Is there some way (compatible on IE9+) that I can listen to changes to a given key on an object without changing the behavior of setting that value?
Your getter/setter idea is a good one...
How about just adding a property definition to your context object?
Add a myLineWidth property to your context object and then set the linewidth using context.myLineWidth instead of context.lineWidth.
Some example code:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
Object.defineProperty(ctx, 'myLineWidth', {
get: function() {
return(this.lineWidth);
},
set: function(newWidth) {
this.lineWidth=newWidth;
console.log("Executed myLineWidth setter: ",this.lineWidth);
}
});
ctx.myLineWidth=5;
ctx.strokeRect(100,100,50,50);
Alternate Method using Encapsulation:
JavaScript does have true inheritance so it's not possible to inherit & override lineWidth.
The next best thing would be encapsulating the context object. Then all coders can use the encapsulated version of the context using the standard property and method syntax (no need for myLineWidth). If needed, here's a how-to: http://aboutcode.net/2011/10/04/efficient-encapsulation-of-javascript-objects.html.
I did a similar encapsulation in order to log the context drawings. Below, I've tried to snip the encapsulation code from one of my projects. You can ignore my special handling of drawImage and gradients as I needed to grab values from these that you won't need to grab--just add those methods to the returnMethods[] array.
Some example code for you to start with:
// Log all context drawings
// Creates a proxy class wrapping canvas context
function LoggedContext(canvas,context) {
var self = this;
this.canvas=canvas;
this.context=context;
this.imageURLs=[];
this.log=[];
this.gradients=[];
this.patterns=[];
this.init(self);
}
// maintain urls of images used
LoggedContext.prototype.imageIndex=function(url){
var i=a.indexOf(url);
// found
if(i>-1){ return(i); }
// not found -- added
a.push(url);
return(a.length-1);
}
///////////////////////////////////////////
// These methods require special handling
// (drawImage:need image.src, gradients:need gradDefs & colors)
//
LoggedContext.prototype.drawImage=function(){
this.context.drawImage.apply(this.context,arguments);
var args = Array.prototype.slice.call(arguments);
args[0]=arguments[0].src;
args.unshift(2,"drawImage");
var sArgs=JSON.stringify(args);
this.log.push(sArgs);
return(this);
}
//
LoggedContext.prototype.createLinearGradient =function(x1,y1,x2,y2){
var gradient=this.context.createLinearGradient(x1,y1,x2,y2);
gradient.context=this;
gradient.gradientID=this.gradients.length;
this.gradients.push({line:{x1:x1,y1:y1,x2:x2,y2:y2},stops:[]});
gradient.baseAddColorStop=gradient.addColorStop;
gradient.addColorStop=function(stop,color){
this.context.gradients[this.gradientID].stops.push({stop:stop,color:color});
this.baseAddColorStop(stop,color);
}
return(gradient);
}
//
LoggedContext.prototype.createPattern =function(i,r){
var pattern=this.context.createPattern(i,r);
pattern.patternID=this.patterns.length;
this.patterns.push({src:i.src,repeat:r});
return(pattern);
}
//
LoggedContext.prototype.createRadialGradient =function(sx,sy,sr,ex,ey,er){
var gradient=this.context.createRadialGradient(sx,sy,sr,ex,ey,er);
gradient.context=this;
gradient.gradientID=this.gradients.length;
this.gradients.push({circles:{sx:sx,sy:sy,sr:sr,ex:ex,ey:ey,er:er},stops:[]});
gradient.baseAddColorStop=gradient.addColorStop;
gradient.addColorStop=function(stop,color){
this.context.gradients[this.gradientID].stops.push({stop:stop,color:color});
this.baseAddColorStop(stop,color);
}
return(gradient);
}
// load the proxy object with all properties & methods of the context
LoggedContext.prototype.init=function(self){
// define public context properties
var properties={
//
fillStyle:"black",
strokeStyle:"black",
lineWidth:1,
font:"10px sans-serif",
//
globalAlpha:1.00,
globalCompositeOperation:"source-over",
//
shadowColor:"black",
shadowBlur:0,
shadowOffsetX:0,
shadowOffsetY:0,
//
lineCap:"butt", // butt,round,square
lineJoin:"miter", // miter,round,miter
miterLimit:10,
//
textAlign:"start",
textBaseLine:"alphabetic",
};
// encapsulate public properties
for (var i in properties) {
(function(i) {
if(!(i=="fillStyle")){
Object.defineProperty(self, i, {
get: function () {
return properties[i];
},
set: function (val) {
this.log.push(JSON.stringify([1,i,val]));
properties[i] = val;
this.context[i]=val;
}
})
}else{
Object.defineProperty(self, i, {
get: function () {
return properties[i];
},
set: function (val) {
if(typeof val ==="object"){
if(val.gradientID>=0){
this.log.push(JSON.stringify([1,i,"gradient",val.gradientID]));
}else if(val.patternID>=0){
this.log.push(JSON.stringify([1,i,"pattern",val.patternID]));
}
}else{
this.log.push(JSON.stringify([1,i,val]));
}
properties[i] = val;
this.context[i]=val;
}
})
}
})(i);
}
// define public context methods
var methods = ['arc','beginPath','bezierCurveTo','clearRect','clip',
'closePath','fill','fillRect','fillText','lineTo','moveTo',
'quadraticCurveTo','rect','restore','rotate','save','scale','setTransform',
'stroke','strokeRect','strokeText','transform','translate','putImageData'];
// encapsulate public methods
for (var i=0;i<methods.length;i++){
var m = methods[i];
this[m] = (function(m){
return function () {
this.context[m].apply(this.context, arguments);
// "arguments" is not a real array--so convert it
var args = Array.prototype.slice.call(arguments);
args.unshift(2,m);
var sArgs=JSON.stringify(args);
this.log.push(sArgs);
return(this);
};}(m));
}
// define context methods that return values
var returnMethods = ['measureText','getImageData','toDataURL',
'isPointInPath','isPointInStroke'];
// encapsulate return methods
for (var i=0;i<returnMethods.length;i++){
var m = returnMethods[i];
this[m] = (function(m){
return function () {
return(this.context[m].apply(this.context, arguments));
};}(m));
}
} // end init()
I have a global variable NS which I can access from the console as such:
NS.some_func();
NS is populated using a method called extendSafe()
some_scope.extendSafe = function (o1, o2) {
var key;
for (key in o2) {
if (o2.hasOwnProperty(key) && o1.hasOwnProperty(key)) {
throw "naming collision: " + key;
}
o1[key] = o2[key];
}
return o1;
};
This is used by setting up a public scope called $P and then copying over to the global scope NS once all the $P methods have been defined.
I want to to it this way so I can verify that I'm not writing over any properties.
This worked well until I tried to save a local variable to $P for later copying to NS. Because the interpreter does not know that $P will be "released" to the window scope, it does not know to keep the local variable active. So I can not use my safeExtend method.
I verified this was the issue by doing a direct copy as such:
NS.local = local;
I can now access NS.local from the console.
However if I copy it over as I wish to do:
$P.local = local;
extendSafe(NS, $P);
The local variable is not available.
How can I safely release it, i.e. using safeExtend()?
Code Snippet
Issue is commented as
// hacked needs a fix
$P.machine = function (obj) {
var pipe,
data_send,
ajax_type,
wait_animation,
set;
wait_animation = document.getElementById('wait_animation');
set = false;
pipe = NS.makePipe(obj);
if ($R.Parsel[pipe.model] === undefined) {
return;
}
time('start');
if ($R.Parsel[pipe.model].hasOwnProperty("pre")) {
pipe = $R.Parsel[pipe.model].pre(pipe);
} else {
return;
}
if (pipe.form_data) {
ajax_type = 'multi';
var form_data = pipe.form_data;
delete pipe.form_data;
form_data.append("pipe", JSON.stringify(pipe));
data_send = form_data;
} else {
ajax_type = 'post';
data_send = 'pipe=' + encodeURIComponent(JSON.stringify(pipe));
}
if (pipe.state === true) {
time('middle');
if (wait_animation) {
set = true;
wait_animation.style.opacity = 1;
}
NS.ajax({
type: ajax_type,
url: NS.Reg.get('path') + NS.Reg.get('path_ajax'),
data: data_send,
callback: function (pipe_string_receive) {
var pass_prefix = pipe_string_receive.slice(0, 3),
times;
if (wait_animation && set) {
wait_animation.style.opacity = 0;
}
if (pass_prefix === '|D|') {
NS.log('|DEBUG| ' + pipe_string_receive.slice(3));
} else if (pass_prefix === '|A|') {
time('middle');
pipe = JSON.parse(pipe_string_receive.slice(3));
if ($R.Parsel[pipe.model].hasOwnProperty("post")) {
pipe = $R.Parsel[pipe.model].post(pipe);
times = time('finish');
pipe.time.pre = times[0];
pipe.time.transit = times[1];
pipe.time.post = times[2];
// works but hacked needs a fix
NS.last = pipe;
// will not exendSafe()
$P.last = pipe;
} else {
return;
}
} else {
throw "<No 'A' or 'D'>" + pipe_string_receive;
}
}
});
}
};
I see you've solved the problem, but I have a feeling that there's something you're misunderstanding about JavaScript:
This worked well until I tried to save a local variable to $P for later copying to NS. Because the interpreter does not know that $P will be "released" to the window scope, it does not know to keep the local variable active. So I can not use my safeExtend method.
I verified this was the issue by doing a direct copy as such:
NS.local = local;
I can now access NS.local from the console.
However if I copy it over as I wish to do:
$P.local = local;
extendSafe(NS, $P);
The local variable is not available.
How can I safely release it, i.e. using safeExtend()?
This doesn't make sense. JavaScript is very good at keeping track of references to objects. If there are any references to an object, it won't garbage collect the object. I have no idea what it could mean to "release an object to the window scope". There isn't really any such concept, just objects and references to them.
I tried looking through your original code, but there's a lot of code there that isn't related to the problem. If you were to simplify it to a minimal test case, I'll bet a simpler solution would become evident.
I do see one issue in your smaller snippet above. You defined your extendSafe() function as some_scope.extendSafe(), but here you're calling it with a plain extendSafe() call and no reference to some_scope. Did it actually call the function? Is this just a typo in the smaller example?
Of course, if you're just happy to have found a solution and want to move on, that's quite understandable! I just have a strong feeling that there's extra code here that you don't need.
I'm having trouble figuring out how I can take a string of an object name and check if that object actually exists.
What I'm trying to accomplish is have an array the defines the required objects for a particular JavaScript "module" to work, for instance:
var requiredImports = ['MyApp.Object1', 'MyApp.Object2'];
Then using requiredImports, I want to loop over them and check if the are defined. Without using the above array, I can do the following which is what I'm trying to accomplish:
if (MyApp.Object1 == undefined) {
alert('Missing MyApp.Object1');
}
But using the above, I'd have to hard code this for every module rather than making a generic method that I can just pass it an array of strings and have it effectively do the same check for me.
I tried doing this by just passing it the objects themselves such as:
var requiredImports = [MyApp.Object1, MyApp.Object2];
But that throws a JavaScript error when those objects do not exist, which is what I'm trying to catch.
var MyApp = {
Object1: {}
};
function exists(varName, scope) {
var parent = scope || window;
try {
varName.split('.').forEach(function (name) {
if (parent[name] === undefined) {
throw 'undefined';
}
parent = parent[name];
});
}
catch (ex) {
return false;
}
return true;
}
console.log(
exists('MyApp.Object1'), // true
exists('MyApp.Object2'), // false
exists('window'), // true
exists('document'), // true
exists('window.document') // true
);
// or
console.log(
['MyApp.Object1', 'MyApp.Object2', 'window', 'document', 'window.document'].filter(function (varName) {
return !exists(varName);
})
);
// => ["MyApp.Object2"]
Note: that forEach is ES5 and as such not implemented in some browsers. But if you'd go with this solution, there is a nice polyfill here.
You can check for definedness with
if ( typeof window['MyApp'] === 'undefined' ||
typeof window['MyApp']['Object1'] === 'undefined' )
{
alert('Missing MyApp.Object1');
}
and so on.
Assuming MyApp.Object1 is a global scope, window is the parent object and since that is the top level object, you don't need to prefix your global vars with it. So window.MyApp.Object1 is the same as MyApp.Object1 (again, assuming this is within global scope).
Also, in javascript, MyApp['Object1'] is the same as MyApp.Object1. So if we apply this principle to the main window object, you can check for window['MyApp'] or window['MyApp']['Object1'] and the key here is that you can replace 'MyApp' and 'Object1' with a variable.
Example:
/* check if a variable/object exists in the global scope) */
function checkIfExists(someVar) {
if (typeof(window[someVar]) == 'undefined')
return true;
return false;
}
var foo = 'bar';
alert(checkIfExists('foo'));
You can evaluate your custom expression in JavaScript. Consider the code below:
var MyApp = {
Object1: "foo",
Object2: "bar"
};
var IsExists = function(varName) {
return new Function('return typeof(' + varName + ') === "undefined" ? false : true;')();
};
USAGE
var requiredImports = ['MyApp.Object1', 'MyApp.Object2'];
for (var i = 0; i < requiredImports.length; i++)
{
alert(requiredImports[i] + ": " + IsExists(requiredImports[i]))
}
You only get error for first level (MyApp in your example). I assume you have only a few first-level requires, so check them manually by window[x] which does not throw:
var requiredTopLevel = ['MyApp'];
for (var i = 0; i < requiredTopLevel.length; ++i) {
if ("undefined" === typeof window[requiredTopLevel[i]]) {
// problem with requiredTopLevel[i]
}
}
and then, to check nested requires (if top-level is present) you can use the values without fear. For example this will work:
var requiredNested = { 'Object1':MyApp.Object1, 'Object2':Myapp.Object2 };
for (var name in requiredNested) {
if ("undefined" === typeof requiredNested[name]) {
// problem with name
}
}
I've started to write few jQuery plugins and figured it'd be nice to setup my IDE with a jQuery plugin template.
I have been reading some articles and posts on this site related to plugin convention, design, etc.. and thought I'd try and consolidate all of that.
Below is my template, I am looking to use it frequently so was keen to ensure it generally conforms to jQuery plugin design convention and whether the idea of having multiple internal methods (or even its general design) would impact performance and be prone to memory issues.
(function($)
{
var PLUGIN_NAME = "myPlugin"; // TODO: Plugin name goes here.
var DEFAULT_OPTIONS =
{
// TODO: Default options for plugin.
};
var pluginInstanceIdCount = 0;
var I = function(/*HTMLElement*/ element)
{
return new Internal(element);
};
var Internal = function(/*HTMLElement*/ element)
{
this.$elem = $(element);
this.elem = element;
this.data = this.getData();
// Shorthand accessors to data entries:
this.id = this.data.id;
this.options = this.data.options;
};
/**
* Initialises the plugin.
*/
Internal.prototype.init = function(/*Object*/ customOptions)
{
var data = this.getData();
if (!data.initialised)
{
data.initialised = true;
data.options = $.extend(DEFAULT_OPTIONS, customOptions);
// TODO: Set default data plugin variables.
// TODO: Call custom internal methods to intialise your plugin.
}
};
/**
* Returns the data for relevant for this plugin
* while also setting the ID for this plugin instance
* if this is a new instance.
*/
Internal.prototype.getData = function()
{
if (!this.$elem.data(PLUGIN_NAME))
{
this.$elem.data(PLUGIN_NAME, {
id : pluginInstanceIdCount++,
initialised : false
});
}
return this.$elem.data(PLUGIN_NAME);
};
// TODO: Add additional internal methods here, e.g. Internal.prototype.<myPrivMethod> = function(){...}
/**
* Returns the event namespace for this widget.
* The returned namespace is unique for this widget
* since it could bind listeners to other elements
* on the page or the window.
*/
Internal.prototype.getEventNs = function(/*boolean*/ includeDot)
{
return (includeDot !== false ? "." : "") + PLUGIN_NAME + "_" + this.id;
};
/**
* Removes all event listeners, data and
* HTML elements automatically created.
*/
Internal.prototype.destroy = function()
{
this.$elem.unbind(this.getEventNs());
this.$elem.removeData(PLUGIN_NAME);
// TODO: Unbind listeners attached to other elements of the page and window.
};
var publicMethods =
{
init : function(/*Object*/ customOptions)
{
return this.each(function()
{
I(this).init(customOptions);
});
},
destroy : function()
{
return this.each(function()
{
I(this).destroy();
});
}
// TODO: Add additional public methods here.
};
$.fn[PLUGIN_NAME] = function(/*String|Object*/ methodOrOptions)
{
if (!methodOrOptions || typeof methodOrOptions == "object")
{
return publicMethods.init.call(this, methodOrOptions);
}
else if (publicMethods[methodOrOptions])
{
var args = Array.prototype.slice.call(arguments, 1);
return publicMethods[methodOrOptions].apply(this, args);
}
else
{
$.error("Method '" + methodOrOptions + "' doesn't exist for " + PLUGIN_NAME + " plugin");
}
};
})(jQuery);
Thanks in advance.
A while back I've build a plugin generator based on a blog article I have read: http://jsfiddle.net/KeesCBakker/QkPBF/. It might be of use. It is fairly basic and straight forward. Any comments would be very welcome.
You can fork your own generator and change it to your needs.
Ps. This is the generated body:
(function($){
//My description
function MyPluginClassName(el, options) {
//Defaults:
this.defaults = {
defaultStringSetting: 'Hello World',
defaultIntSetting: 1
};
//Extending options:
this.opts = $.extend({}, this.defaults, options);
//Privates:
this.$el = $(el);
}
// Separate functionality from object creation
MyPluginClassName.prototype = {
init: function() {
var _this = this;
},
//My method description
myMethod: function() {
var _this = this;
}
};
// The actual plugin
$.fn.myPluginClassName = function(options) {
if(this.length) {
this.each(function() {
var rev = new MyPluginClassName(this, options);
rev.init();
$(this).data('myPluginClassName', rev);
});
}
};
})(jQuery);
[Edit] 7 months later
Quoting from the github project
jQuery is no good, and jQuery plugins is not how do modular code.
Seriously "jQuery plugins" are not a sound architecture strategy. Writing code with a hard dependency on jQuery is also silly.
[Original]
Since I gave critique about this template I will propose an alternative.
To make live easier this relies on jQuery 1.6+ and ES5 (use the ES5 Shim).
I've spend some time re-designing the plugin template you've given and rolled out my own.
Links:
Github
Documentation
Unit tests Confirmed to pass in FF4, Chrome and IE9 (IE8 & OP11 dies. known bug).
Annotated Source Code
The PlaceKitten example plugin
Comparison:
I've refactored the template so that it's split into boilerplate (85%) and scaffolding code (15%). The intention is that you only have to edit the scaffolding code and you can keep leave boilerplate code untouched. To achieve this I've used
inheritance var self = Object.create(Base) Rather then editing the Internal class you have directly you should be editing a sub class. All your template / default functionality should be in a base class (called Base in my code).
convention self[PLUGIN_NAME] = main; By convention the plugin defined on jQuery will call the method define on self[PLUGIN_NAME] by default. This is considered the main plugin method and has a seperate external method for clarity.
monkey patching $.fn.bind = function _bind ... Use of monkey patching means that the event namespacing is done automatically for you under the hood. This functionality is free and does not come at the cost of readability (calling getEventNS all the time).
OO Techniques
It's better to stick to proper JavaScript OO rather then classical OO emulation. To achieve this you should use Object.create. (which ES5 just use the shim to upgrade old browsers).
var Base = (function _Base() {
var self = Object.create({});
/* ... */
return self;
})();
var Wrap = (function _Wrap() {
var self = Object.create(Base);
/* ... */
return self;
})();
var w = Object.create(Wrap);
This is different from the standard new and .prototype based OO people are used to. This approach is preferred because it re-inforces the concept that there are only Objects in JavaScript and it's a prototypical OO approach.
[getEventNs]
As mentioned this method has been refactored away by overriding .bind and .unbind to automatically inject namespaces. These methods are overwritten on the private version of jQuery $.sub(). The overwritten methods behave the same way as your namespacing does. It namespaces events uniquely based on plugin and instance of a plugin wrapper around a HTMLElement (Using .ns.
[getData]
This method has been replaced with a .data method that has the same API as jQuery.fn.data. The fact that it's the same API makes it easier to use, its basically a thin wrapper around jQuery.fn.data with namespacing. This allows you to set key/value pair data that is immediatley stored for that plugin only. Multiple plugins can use this method in parallel without any conflicts.
[publicMethods]
The publicMethods object has been replaced by any method being defined on Wrap being automatically public. You can call any method on a Wrapped object directly but you do not actually have access to the wrapped object.
[$.fn[PLUGIN_NAME]]
This has been refactored so it exposes a more standardized API. This api is
$(selector).PLUGIN_NAME("methodName", {/* object hash */}); // OR
$(selector).PLUGIN_NAME({/* object hash */}); // methodName defaults to PLUGIN_NAME
the elements in the selector are automatically wrapped in the Wrap object, the method is called or each selected element from the selector and the return value is always a $.Deferred element.
This standardizes the API and the return type. You can then call .then on the returned deferred to get out the actual data you care about. The use of deferred here is very powerful for abstraction away whether the plugin is synchronous or asynchronous.
_create
A caching create function has been added. This is called to turn a HTMLElement into a Wrapped element and each HTMLElement will only be wrapped once. This caching gives you a solid reduction in memory.
$.PLUGIN_NAME
Added another public method for the plugin (A total of two!).
$.PLUGIN_NAME(elem, "methodName", {/* options */});
$.PLUGIN_NAME([elem, elem2, ...], "methodName", {/* options */});
$.PLUGIN_NAME("methodName", {
elem: elem, /* [elem, elem2, ...] */
cb: function() { /* success callback */ }
/* further options */
});
All parameters are optional. elem defaults to <body>, "methodName" defaults to "PLUGIN_NAME" and {/* options */} defaults to {}.
This API is very flexible (with 14 method overloads!) and standard enough to get used to the syntnax for every method your plugin will expose.
Public exposure
The Wrap, create and $ objects are exposed globally. This will allow advanced plugin users maximum flexibility with your plugin. They can use create and the modified subbed $ in their development and they can also monkey patch Wrap. This allows for i.e. hooking into your plugin methods. All three of these are marked with a _ in front of their name so they are internal and using them breaks the garantuee that your plugin works.
The internal defaults object is also exposed as $.PLUGIN_NAME.global. This allows users to override your defaults and set plugin global defaults. In this plugin setup all hashes past into methods as objects are merged with the defaults, so this allows users to set global defaults for all your methods.
Actual Code
(function($, jQuery, window, document, undefined) {
var PLUGIN_NAME = "Identity";
// default options hash.
var defaults = {
// TODO: Add defaults
};
// -------------------------------
// -------- BOILERPLATE ----------
// -------------------------------
var toString = Object.prototype.toString,
// uid for elements
uuid = 0,
Wrap, Base, create, main;
(function _boilerplate() {
// over-ride bind so it uses a namespace by default
// namespace is PLUGIN_NAME_<uid>
$.fn.bind = function _bind(type, data, fn, nsKey) {
if (typeof type === "object") {
for (var key in type) {
nsKey = key + this.data(PLUGIN_NAME)._ns;
this.bind(nsKey, data, type[key], fn);
}
return this;
}
nsKey = type + this.data(PLUGIN_NAME)._ns;
return jQuery.fn.bind.call(this, nsKey, data, fn);
};
// override unbind so it uses a namespace by default.
// add new override. .unbind() with 0 arguments unbinds all methods
// for that element for this plugin. i.e. calls .unbind(_ns)
$.fn.unbind = function _unbind(type, fn, nsKey) {
// Handle object literals
if ( typeof type === "object" && !type.preventDefault ) {
for ( var key in type ) {
nsKey = key + this.data(PLUGIN_NAME)._ns;
this.unbind(nsKey, type[key]);
}
} else if (arguments.length === 0) {
return jQuery.fn.unbind.call(this, this.data(PLUGIN_NAME)._ns);
} else {
nsKey = type + this.data(PLUGIN_NAME)._ns;
return jQuery.fn.unbind.call(this, nsKey, fn);
}
return this;
};
// Creates a new Wrapped element. This is cached. One wrapped element
// per HTMLElement. Uses data-PLUGIN_NAME-cache as key and
// creates one if not exists.
create = (function _cache_create() {
function _factory(elem) {
return Object.create(Wrap, {
"elem": {value: elem},
"$elem": {value: $(elem)},
"uid": {value: ++uuid}
});
}
var uid = 0;
var cache = {};
return function _cache(elem) {
var key = "";
for (var k in cache) {
if (cache[k].elem == elem) {
key = k;
break;
}
}
if (key === "") {
cache[PLUGIN_NAME + "_" + ++uid] = _factory(elem);
key = PLUGIN_NAME + "_" + uid;
}
return cache[key]._init();
};
}());
// Base object which every Wrap inherits from
Base = (function _Base() {
var self = Object.create({});
// destroy method. unbinds, removes data
self.destroy = function _destroy() {
if (this._alive) {
this.$elem.unbind();
this.$elem.removeData(PLUGIN_NAME);
this._alive = false;
}
};
// initializes the namespace and stores it on the elem.
self._init = function _init() {
if (!this._alive) {
this._ns = "." + PLUGIN_NAME + "_" + this.uid;
this.data("_ns", this._ns);
this._alive = true;
}
return this;
};
// returns data thats stored on the elem under the plugin.
self.data = function _data(name, value) {
var $elem = this.$elem, data;
if (name === undefined) {
return $elem.data(PLUGIN_NAME);
} else if (typeof name === "object") {
data = $elem.data(PLUGIN_NAME) || {};
for (var k in name) {
data[k] = name[k];
}
$elem.data(PLUGIN_NAME, data);
} else if (arguments.length === 1) {
return ($elem.data(PLUGIN_NAME) || {})[name];
} else {
data = $elem.data(PLUGIN_NAME) || {};
data[name] = value;
$elem.data(PLUGIN_NAME, data);
}
};
return self;
})();
// Call methods directly. $.PLUGIN_NAME(elem, "method", option_hash)
var methods = jQuery[PLUGIN_NAME] = function _methods(elem, op, hash) {
if (typeof elem === "string") {
hash = op || {};
op = elem;
elem = hash.elem;
} else if ((elem && elem.nodeType) || Array.isArray(elem)) {
if (typeof op !== "string") {
hash = op;
op = null;
}
} else {
hash = elem || {};
elem = hash.elem;
}
hash = hash || {}
op = op || PLUGIN_NAME;
elem = elem || document.body;
if (Array.isArray(elem)) {
var defs = elem.map(function(val) {
return create(val)[op](hash);
});
} else {
var defs = [create(elem)[op](hash)];
}
return $.when.apply($, defs).then(hash.cb);
};
// expose publicly.
Object.defineProperties(methods, {
"_Wrap": {
"get": function() { return Wrap; },
"set": function(v) { Wrap = v; }
},
"_create":{
value: create
},
"_$": {
value: $
},
"global": {
"get": function() { return defaults; },
"set": function(v) { defaults = v; }
}
});
// main plugin. $(selector).PLUGIN_NAME("method", option_hash)
jQuery.fn[PLUGIN_NAME] = function _main(op, hash) {
if (typeof op === "object" || !op) {
hash = op;
op = null;
}
op = op || PLUGIN_NAME;
hash = hash || {};
// map the elements to deferreds.
var defs = this.map(function _map() {
return create(this)[op](hash);
}).toArray();
// call the cb when were done and return the deffered.
return $.when.apply($, defs).then(hash.cb);
};
}());
// -------------------------------
// --------- YOUR CODE -----------
// -------------------------------
main = function _main(options) {
this.options = options = $.extend(true, defaults, options);
var def = $.Deferred();
// Identity returns this & the $elem.
// TODO: Replace with custom logic
def.resolve([this, this.elem]);
return def;
}
Wrap = (function() {
var self = Object.create(Base);
var $destroy = self.destroy;
self.destroy = function _destroy() {
delete this.options;
// custom destruction logic
// remove elements and other events / data not stored on .$elem
$destroy.apply(this, arguments);
};
// set the main PLUGIN_NAME method to be main.
self[PLUGIN_NAME] = main;
// TODO: Add custom logic for public methods
return self;
}());
})(jQuery.sub(), jQuery, this, document);
As can be seen the code your supposed to edit is below the YOUR CODE line. The Wrap object acts similarly to your Internal object.
The function main is the main function called with $.PLUGIN_NAME() or $(selector).PLUGIN_NAME() and should contain your main logic.
How about something like this ? It's much clearer but again it would be nice to hear from you if you can improve it without overcomplicating its simplicity.
// jQuery plugin Template
(function($){
$.myPlugin = function(options) { //or use "$.fn.myPlugin" or "$.myPlugin" to call it globaly directly from $.myPlugin();
var defaults = {
target: ".box",
buttons: "li a"
};
options = $.extend(defaults, options);
function logic(){
// ... code goes here
}
//DEFINE WHEN TO RUN THIS PLUGIN
$(window).on('load resize', function () { // Load and resize as example ... use whatever you like
logic();
});
// RETURN OBJECT FOR CHAINING
// return this;
// OR FOR FOR MULTIPLE OBJECTS
// return this.each(function() {
// // Your code ...
// });
};
})(jQuery);
// USE EXAMPLE with default settings
$.myPlugin(); // or run plugin with default settings like so.
// USE EXAMPLE with overwriten settings
var options = {
target: "div.box", // define custom options
buttons: ".something li a" // define custom options
}
$.myPlugin(options); //or run plugin with overwriten default settings
I've been googling and landed here so, I have to post some ideas: first I agree with #Raynos.
The most code out there that tries to build a jQuery plugin actually...is not a plugin! It's just an object stored in memory which is refered by the data property of a node/element. That's because jQuery should be seen and used as a tool side by side with a class library (to remedy js inconsistencies from OO architecture) to build better code and yes this is not bad at all!
If you don't like classical OO behaviour stick to a prototypal library like clone.
So what our options really?
use JQueryUI/Widget or a similar library that hides technicalities and
provides abstraction
don't use them because of complexities, learning curve and god knows future changes
don't use them becuase you want to insist on modular design, build small-increase later
don't use them because you might want porting/connecting your code with different libraries.
Suppose the issues addressed by the following scenario (see the complexities from this question: Which jQuery plugin design pattern should I use?):
we have nodes A, B and C that store an object reference into their data property
some of them store info in public and private accessible internal objects,
some classes of these objects are connected with inheritance,
all of these nodes also need some private and public singletons to work best.
What would we do? See the drawning:
classes : | A B C
------------------case 1----------
members | | | |
of | v v v
an object | var a=new A, b=new B, c=new C
at | B extends A
node X : | a, b, c : private
------------------case 2---------
members | | | |
of | v v v
an object | var aa=new A, bb=new B, cc=new C
at | BB extends AA
node Y : | aa, bb, cc : public
-------------------case 3--------
members | | | |
of | v v v
an object | var d= D.getInstance() (private),
at | e= E.getInstance() (public)
node Z : | D, E : Singletons
as you can see every node refers to an object - a jQuery approach - but these objects change wildely; they contain object-properties with different data stored in or, even singletons that should be...single in memory like the prototype functions of the objects. We don't want every object's function belonging to class A to be repeatedly duplicated in memory in every node's object!
Before my answer see a common approach I've seen in jQuery plugins - some of them very popular but I don't say names:
(function($, window, document, undefined){
var x = '...', y = '...', z = '...',
container, $container, options;
var myPlugin = (function(){ //<----the game is lost!
var defaults = {
};
function init(elem, options) {
container = elem;
$container = $(elem);
options = $.extend({}, defaults, options);
}
return {
pluginName: 'superPlugin',
init: function(elem, options) {
init(elem, options);
}
};
})();
//extend jquery
$.fn.superPlugin = function(options) {
return this.each(function() {
var obj = Object.create(myPlugin); //<---lose, lose, lose!
obj.init(this, options);
$(this).data(obj.pluginName, obj);
});
};
}(jQuery, window, document));
I was watching some slides at: http://www.slideshare.net/benalman/jquery-plugin-creation from Ben Alman where he refers at slide 13 to object literals as singletons and that just knock me over: this is what the above plugin does, it creates one singleton with no chance whatsover to alter it's internal state!!!
Furthermore, at the jQuery part it stores a common reference to every single node!
My solution uses a factory to keep internal state and return an object plus it can be expanded with a class library and split in different files:
;(function($, window, document, undefined){
var myPluginFactory = function(elem, options){
........
var modelState = {
options: null //collects data from user + default
};
........
function modeler(elem){
modelState.options.a = new $$.A(elem.href);
modelState.options.b = $$.B.getInstance();
};
........
return {
pluginName: 'myPlugin',
init: function(elem, options) {
init(elem, options);
},
get_a: function(){return modelState.options.a.href;},
get_b: function(){return modelState.options.b.toString();}
};
};
//extend jquery
$.fn.myPlugin = function(options) {
return this.each(function() {
var plugin = myPluginFactory(this, options);
$(this).data(plugin.pluginName, plugin);
});
};
}(jQuery, window, document));
My project: https://github.com/centurianii/jsplugin
See: http://jsfiddle.net/centurianii/s4J2H/1/