Note that there are some explanatory texts on larger screens.

plurals
  1. POjQuery plugin return value from method and still preserve chainability
    primarykey
    data
    text
    <p>I currently reworking my personal jQuery plugin starting point, but I stuck at a small and annoying problem. If a public method is called, it returns the the object it was called from and not the value.</p> <p>Here's my actual point where I start from:</p> <pre><code>;(function($, window, document, undefined) { 'use strict'; var pluginName = 'defaultPluginName', defaults = { foo: 'foo', bar: 'bar' }, settingsKey = pluginName + '-settings'; var init = function(options) { var elem = this, $elem = $(this), settings = $.extend({}, defaults, options); $elem.data(settingsKey, settings); }; var callMethod = function(method, options) { var methodFn = $[pluginName].addMethod[method], args = Array.prototype.slice.call(arguments); if (methodFn) { this.each(function() { var opts = args.slice(1), settings = $(this).data(settingsKey); opts.unshift(settings); methodFn.apply(this, opts); }); } }; $[pluginName] = { settingsKey: settingsKey, addMethod: { option: function(settings, key, val) { if (val) { settings[key] = val; } else if (key) { return settings[key]; // returns the value from settings } } } }; $.fn[pluginName] = function(options) { if (typeof options === 'string') { callMethod.apply(this, arguments); } else { init.call(this, options); } return this; }; }(window.jQuery || window.Zepto, window, document)); </code></pre> <p>However, I initialize the plugin it and call a method...</p> <pre><code>$('div').defaultPluginName(); console.log($('div').defaultPluginName('option', 'foo')); </code></pre> <p>it returns: <code>[&lt;div&gt;, &lt;div&gt;, prevObject: jQuery.fn.jQuery.init[1], context: #document, selector: "div"]</code> and not <code>'foo'</code> as (from where the comment is) excepted.</p> <p>So the question is, is it possible to return the value from a public method and still preserve the chainability? And if you have time and fun to help me, i would be glad about some examples ;)</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. 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