以前の記事で、jQueryのプラグインを簡単に作成してみたが、まだまだ融通が利かない。
そこで、いろんなライブラリを解読してみて、そこそこ使える形式が見えてきたので記載する。
この記述方法だと、内部からも外部からも関数をコールできるので、後にパラメータを渡すことができる。
jquery.sample.js
[javascript]
/*
* 自作プラグインサンプル
*/
;(function($){
var sample = function(target, opts){
//デフォルトパラメータ
this.defaults = {
param : ‘hoge’,
params : [{title : ‘DefTitle1’, name: ‘DefName1’, id: ‘111’ },
{title : ‘DefTitle2’, name: ‘DefName2’, id: ‘222’ }
],
width : ‘1200px’
}
//パラメータ上書き
$.extend(this.defaults, opts || {});
//関数コール
this.init();
this.reload(this.defaults.width);
}
//関数定義
sample.prototype = {
init: function() {
alert("Init:" + this.defaults.param);
},
reload: function(str) {
alert("Reload:" + str);
}
};
//—————–
// エントリポイント
//—————–
$.fn.sample = function(options){
//オプション取得
opts = jQuery.extend({}, $.fn.sample.defaults, options);
// return this.each(function(){
// new sample(this, options, temp);
// });
if ( $(this).length > 1) {
var _instances = [];
$(this).each(function(i) {
_instances[i] = new sample(this, options);
});
return _instances;
} else {
return new sample(this, options);
}
};
//—————–
//デフォルト値
//—————–
// $.fn.sample.defaults = {
// param : ‘hoge’,
// params : [{title : ‘defTitle1’, name: ‘defName1’, id: ‘111’ },
// {title : ‘defTitle2’, name: ‘defName2’, id: ‘222’ }
// ],
// width : ‘1200px’
// };
})(jQuery);
[/javascript]
コールする側 [HTML]
[html]
<script type="text/javascript">
$("#sample").sample({param:’moge’}).reload(‘hage!!’);
</script>
<div id="sample"></div>
[/html]
但し、十分な検証はしていないので、自己責任で参考にしてください。