Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>[Edit]</strong> 7 months later</p> <p>Quoting from the github project</p> <blockquote> <p>jQuery is no good, and jQuery plugins is not how do modular code.</p> </blockquote> <p>Seriously "jQuery plugins" are not a sound architecture strategy. Writing code with a hard dependency on jQuery is also silly.</p> <p><strong>[Original]</strong></p> <p>Since I gave critique about this template I will propose an alternative.</p> <p>To make live easier this relies on <code>jQuery</code> 1.6+ and ES5 (use the <a href="https://github.com/Raynos/jQuery-plugin-scaffolding" rel="noreferrer">ES5 Shim</a>).</p> <p>I've spend some time re-designing the plugin template you've given and rolled out my own.</p> <p><strong>Links:</strong></p> <ul> <li><a href="https://github.com/Raynos/jQuery-plugin-scaffolding" rel="noreferrer">Github</a></li> <li><a href="http://raynos.github.com/jQuery-plugin-scaffolding/" rel="noreferrer">Documentation</a></li> <li><a href="http://raynos.github.com/jQuery-plugin-scaffolding/tests/test.html" rel="noreferrer">Unit tests</a> Confirmed to pass in FF4, Chrome and IE9 (IE8 &amp; OP11 dies. known <a href="https://github.com/kriskowal/es5-shim/pull/20" rel="noreferrer">bug</a>).</li> <li><a href="http://raynos.github.com/jQuery-plugin-scaffolding/docs/jQuery-plugin-scaffold.html" rel="noreferrer">Annotated Source Code</a></li> <li><a href="http://jsfiddle.net/e2aYH/11/" rel="noreferrer">The PlaceKitten example plugin</a></li> </ul> <p><strong>Comparison:</strong></p> <p>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 </p> <ul> <li><em>inheritance</em> <a href="https://github.com/Raynos/jQuery-plugin-scaffolding/blob/master/lib/jQuery-plugin-scaffold.js#L210" rel="noreferrer"><code>var self = Object.create(Base)</code></a> Rather then editing the <code>Internal</code> class you have directly you should be editing a sub class. All your template / default functionality should be in a base class (called <code>Base</code> in my code).</li> <li><em>convention</em> <a href="https://github.com/Raynos/jQuery-plugin-scaffolding/blob/master/lib/jQuery-plugin-scaffold.js#L222" rel="noreferrer"><code>self[PLUGIN_NAME] = main;</code></a> By convention the plugin defined on jQuery will call the method define on <code>self[PLUGIN_NAME]</code> by default. This is considered the <code>main</code> plugin method and has a seperate external method for clarity. </li> <li><em>monkey patching</em> <a href="https://github.com/Raynos/jQuery-plugin-scaffolding/blob/master/lib/jQuery-plugin-scaffold.js#L20" rel="noreferrer"><code>$.fn.bind = function _bind ...</code></a> 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 <code>getEventNS</code> all the time).</li> </ul> <p><strong>OO Techniques</strong></p> <p>It's better to stick to proper JavaScript OO rather then classical OO emulation. To achieve this you should use <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/create" rel="noreferrer"><code>Object.create</code></a>. (which ES5 just use the shim to upgrade old browsers).</p> <pre><code>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); </code></pre> <p>This is different from the standard <code>new</code> and <code>.prototype</code> 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.</p> <p><strong>[<code>getEventNs</code>]</strong></p> <p>As mentioned this method has been refactored away by overriding <code>.bind</code> and <code>.unbind</code> to automatically inject namespaces. These methods are overwritten on the private version of jQuery <a href="https://github.com/Raynos/jQuery-plugin-scaffolding/blob/master/lib/jQuery-plugin-scaffold.js#L229" rel="noreferrer"><code>$.sub()</code></a>. 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 <a href="https://github.com/Raynos/jQuery-plugin-scaffolding/blob/master/lib/jQuery-plugin-scaffold.js#L23" rel="noreferrer"><code>.ns</code></a>.</p> <p><strong>[<code>getData</code>]</strong></p> <p>This method has been replaced with a <a href="https://github.com/Raynos/jQuery-plugin-scaffolding/blob/master/lib/jQuery-plugin-scaffold.js#L105" rel="noreferrer"><code>.data</code></a> method that has the same API as <code>jQuery.fn.data</code>. The fact that it's the same API makes it easier to use, its basically a thin wrapper around <code>jQuery.fn.data</code> 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.</p> <p><strong>[<code>publicMethods</code>]</strong></p> <p>The publicMethods object has been replaced by any method being defined on <code>Wrap</code> being automatically public. You can call any method on a Wrapped object directly but you do not actually have access to the wrapped object.</p> <p><strong>[<code>$.fn[PLUGIN_NAME]</code>]</strong></p> <p>This has been refactored so it exposes a more standardized API. This api is</p> <pre><code>$(selector).PLUGIN_NAME("methodName", {/* object hash */}); // OR $(selector).PLUGIN_NAME({/* object hash */}); // methodName defaults to PLUGIN_NAME </code></pre> <p>the elements in the selector are automatically wrapped in the <code>Wrap</code> object, the method is called or each selected element from the selector and the return value is always a <a href="http://api.jquery.com/category/deferred-object/" rel="noreferrer"><code>$.Deferred</code></a> element. </p> <p>This standardizes the API and the return type. You can then call <code>.then</code> 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.</p> <p><a href="https://github.com/Raynos/jQuery-plugin-scaffolding/blob/master/lib/jQuery-plugin-scaffold.js#L55" rel="noreferrer"><strong><code>_create</code></strong></a></p> <p>A caching create function has been added. This is called to turn a <code>HTMLElement</code> into a Wrapped element and each HTMLElement will only be wrapped once. This caching gives you a solid reduction in memory.</p> <p><a href="https://github.com/Raynos/jQuery-plugin-scaffolding/blob/master/lib/jQuery-plugin-scaffold.js#L127" rel="noreferrer"><strong><code>$.PLUGIN_NAME</code></strong></a></p> <p>Added another public method for the plugin (A total of two!).</p> <pre><code>$.PLUGIN_NAME(elem, "methodName", {/* options */}); $.PLUGIN_NAME([elem, elem2, ...], "methodName", {/* options */}); $.PLUGIN_NAME("methodName", { elem: elem, /* [elem, elem2, ...] */ cb: function() { /* success callback */ } /* further options */ }); </code></pre> <p>All parameters are optional. <code>elem</code> defaults to <code>&lt;body&gt;</code>, <code>"methodName"</code> defaults to <code>"PLUGIN_NAME"</code> and <code>{/* options */}</code> defaults to <code>{}</code>.</p> <p>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.</p> <p><a href="https://github.com/Raynos/jQuery-plugin-scaffolding/blob/master/lib/jQuery-plugin-scaffold.js#L157" rel="noreferrer"><strong>Public exposure</strong></a></p> <p>The <code>Wrap</code>, <code>create</code> and <code>$</code> objects are exposed globally. This will allow advanced plugin users maximum flexibility with your plugin. They can use <code>create</code> and the modified subbed <code>$</code> in their development and they can also monkey patch <code>Wrap</code>. This allows for i.e. hooking into your plugin methods. All three of these are marked with a <code>_</code> in front of their name so they are internal and using them breaks the garantuee that your plugin works.</p> <p>The internal <code>defaults</code> object is also exposed as <code>$.PLUGIN_NAME.global</code>. This allows users to override your defaults and set plugin global <code>defaults</code>. 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. </p> <p><a href="http://raynos.github.com/jQuery-plugin-scaffolding/" rel="noreferrer"><strong>Actual Code</strong></a></p> <pre><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_&lt;uid&gt; $.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" &amp;&amp; !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 &amp;&amp; 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 &amp; 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); </code></pre> <p>As can be seen the code your supposed to edit is below the <code>YOUR CODE</code> line. The <code>Wrap</code> object acts similarly to your <code>Internal</code> object. </p> <p>The function <code>main</code> is the main function called with <code>$.PLUGIN_NAME()</code> or <code>$(selector).PLUGIN_NAME()</code> and should contain your main logic.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload