I'm trying to learn learning javascript and jQuery plugin standards, and after some googling and testing I've come up with this pattern:
;(function(window, document, ,ドル undefined){
var plugin = function(element){
var instance = this,
somePrivateFunc = function(){
console.log(instance.options);
};
this.options = $(element).data();
this.publicFunc = function(){
somePrivateFunc();
};
}
$.fn.myplugin = function(){
return this.each(function(){
if(!$(this).data('_myplugin')){
var myplugin = new plugin(this);
myplugin.publicFunc();
$(this).data('_myplugin', myplugin);
}
});
}
}(window, document, jQuery));
Example
Is this OK? Do you have any suggestions on improving it? Thanks!
1 Answer 1
Here are some suggestions:
Use
$.data(this, '_myplugin')
&$.data(this, '_myplugin', myplugin)
. They're SO MUCH faster.Since you call
.publicFunc
every time you instantiate your plugin, you should probably move the call into your constructor instead.Public functions should be assigned to the prototype, so that we don't create a new function every time we create a new instance.
Likewise, define a private function outside of the constructor, in the parent closure. Again, we don't want to have to re-create the same function over and over again.
;(function ( window, document, $ ) {
function somePrivateFunc ( instance ) {
console.log( instance.options );
}
var Plugin = function( element ) {
// What is this?
this.options = $(element).data();
this.publicFunc();
}
Plugin.prototype.publicFunc = function () {
somePrivateFunc( this );
};
$.fn.myplugin = function () {
return this.each(function () {
if ( ! $.data(this, '_myplugin') ) {
$.data( this, '_myplugin', new Plugin(this) );
}
});
};
}(window, document, jQuery));
P.S. You haven't described how you're exposing the plugin's additional methods. For that you should read the jQuery plugin creation tutorial.
Find the section titled Provide Public Access to Secondary Functions as Applicable.
;
for? \$\endgroup\$