アクセス可能なメソッドとオプションを備えたプラグインを構築したいと考えています。これは複雑なプラグイン用です。プラグインの外部でメソッドにアクセスできるようにする必要があります。これは、誰かが DOM に何かを広告した場合、それを更新する必要があるためです (したがって、完全なプラグインを再度実行する必要はありません)。
過去にこのようなプラグインがあるのを見たことがありますが、それらを見つけることができないので、それらを見ることはできません. 私はまだjavascriptに慣れていないので、どんな助けでもいいでしょう。
オプションをグローバルにオーバーライドできると便利です。
プラグインの使用方法:
// options
$('#someid').myplugin({name: 'hello world'});
// methods(would be nice if we can use this)
$('#someid').myplugin('update');
// 古いプラグイン ラッパー
;(function($, window, document, undefined){
$.fn.pluginmyPlugin = function(options) {
options = $.extend({}, $.fn.pluginmyPlugin.options, options);
return this.each(function() {
var obj = $(this);
// the code
});
};
/**
* Default settings(dont change).
* You can globally override these options
* by using $.fn.pluginName.key = 'value';
**/
$.fn.pluginmyPlugin.options = {
name: '',
...
};
})(jQuery, window, document);
アップデート
したがって、jQuery のドキュメントを参照した後、次のコードを作成しました。コードに何か問題がある場合はお知らせください。
;(function($, window, document, undefined){
var methods = {
init : function( options ) {
options = $.extend({}, $.fn.pluginmyPlugin.options, options);
return this.each(function(){
alert('yes i am the main code')
});
},
update : function( ) {
alert('updated')
}
};
$.fn.pluginmyPlugin = function(method) {
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 this plugin' );
}
};
/**
* Default settings(dont change).
* You can globally override these options
* by using $.fn.pluginName.key = 'value';
**/
$.fn.pluginmyPlugin.options = {
name: 'john doe',
//....
};
})(jQuery, window, document);