很高兴在我得到赏金之后,我发现了一个非常好的网站,它解释了如何使用.data()来公开plubic属性和方法。
在这里您可以找到整个博客文章:
building object oriented jquery plugin
.
这是上面链接中的整个示例,因此所有的文章都归博客作者所有。
(function($){
var MyPlugin = function(element, options)
{
var elem = $(element);
var obj = this;
var settings = $.extend({
param: 'defaultValue'
}, options || {});
// Public method - can be called from client code
this.publicMethod = function()
{
console.log('public method called!');
};
// Private method - can only be called from within this object
var privateMethod = function()
{
console.log('private method called!');
};
};
$.fn.myplugin = function(options)
{
return this.each(function()
{
var element = $(this);
// Return early if this element already has a plugin instance
if (element.data('myplugin')) return;
// pass options to plugin constructor
var myplugin = new MyPlugin(this, options);
// Store plugin object in this element's data
element.data('myplugin', myplugin);
});
};
})(jQuery);