jQueryプラグインに取り組んでいますが、jQueryのベストプラクティスのデフォルトとオプション、データと名前空間の手法を組み合わせたデザインパターンに問題があります。これが私のコードの抽象化されたバージョンです:
(function($) {
var defaults = {
key1: 'value1',
key2: 'value2'
};
var settings = {};
var methods = {
init: function() {
return this.each(function() {
var $this = $(this), data = $this.data('pluginname');
console.log('init called');
// If the plugin hasn't been initialized yet
if (!data) {
//Do more setup stuff here
$this.data('pluginname', {
key3: 'value3',
key4: 'value4'
});
}
//test for settings and data
console.log(settings);
console.log(data);
});
},
methodname: function() {
return this.each(function() {
var $this = $(this), data = $this.data('pluginname');
console.log('methodname called');
//test for settings and data
console.log(settings);
console.log(data);
});
}
};
$.fn.pluginname = function(method, options) {
settings = $.extend({}, defaults, options);
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 {
$.error( 'Method ' + method + ' does not exist on jQuery.pluginname' );
}
};
$(document).ready(function() {
$('body').pluginname();
$('body').pluginname('methodname', {key1: 'overriding default value for key 1'});
});
})(jQuery);
そのコードを最新バージョンのjQueryで実行すると、init
とmethodname
関数の両方を呼び出し、それぞれにsettings
とdata
オブジェクトを記録していることがわかります。呼び出しでは、とのmethodname
両方にアクセスできますsettings
がdata
、init
呼び出し自体では、data
オブジェクトは未定義を返します。21行目のスクリプトにブレークポイントを設定すると、コンソールでdata
オブジェクトをコールバックできます。$this.data('pluginname')
誰かが私がここで間違っていることを見ますか?data.key3
init、functionの中に書くことができるはずですよね?