現在、個人用の jQuery プラグインの出発点を作り直していますが、小さくて厄介な問題で立ち往生しています。パブリック メソッドが呼び出されると、値ではなく、呼び出し元のオブジェクトが返されます。
これが私が始める実際のポイントです:
;(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));
ただし、プラグインを初期化し、メソッドを呼び出します...
$('div').defaultPluginName();
console.log($('div').defaultPluginName('option', 'foo'));
それは次を返します: [<div>, <div>, prevObject: jQuery.fn.jQuery.init[1], context: #document, selector: "div"]
and not 'foo'
as (コメントがある場所から) 例外。
問題は、パブリック メソッドから値を返し、チェーン可能性を維持することは可能かということです。そして、私を助けるために時間と楽しみがあれば、いくつかの例を教えていただければ幸いです;)