我们正在改变我们的核心jQuery插件模板。下面是一个模拟样本。我遇到的问题是:
我们如何获得封闭插件中的这个?
;(function( $, window, document, undefined ){
var pluginName = 'myPlugin',
defaults = {
data : null,
el : null,
$el : null
}
function Plugin(el, options) {
this.el = el;
this.$el = $(el);
this.options = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.methods.init();
}
$.extend(Plugin.prototype, {
methods: {
init: function() {
functions._addInput.call(this);
},
destroy: function () {
console.log('in public destroy');
this.$el.removeData();
},
testMessage: function() {
console.log('in public testMessage()');
},
inputHandler: function(value) {
functions._inputHandler(value);
}
}
});
/*
----------------------------
PRIVATE FUNCTIONS
----------------------------
*/
var functions = {
_addInput: function() {
var $this = this;
console.log('adding input');
var input = '<input type="text" class="myplugin-input">';
$this.$el.append(input);
},
_testMessage: function() {
console.log('in the private testMessage()');
},
_inputHandler: function(value) {
console.log(value);
}
};
//* Plugin Function
$.fn.myPlugin = function() {
var args = Array.prototype.slice.call(arguments, 0),
options,
base,
method, value,
allowedMethods = ["destroy", "testMessage", "inputHandler"];
this.each(function(){
if (args.length === 0 || typeof args[0] === 'object')
{
if ( ! $.data( this, pluginName))
{
options = args.length === 0 ? {} : $.extend({}, $.fn.myPlugin.defaults, args[0]);
options.el = $(this);
$.data( this, pluginName, new Plugin( this, options ));
}
}
else if (typeof args[0] === 'string')
{
if ( ! args[0] in allowedMethods) throw 'Unknown method ' + args[0] + ' passed to myPlugin';
base = $.data(this, pluginName);
if (base === undefined) return this;
method = args[0];
base.methods[method].apply(base, args.slice(1));
}
else
{
throw 'Invalid arguments pased to myPlugin plugin ' + args;
}
return (value === undefined) ? this : value;
});
};
$.fn.myPlugin.defaults = {
data : null,
el : null,
};
})(jQuery, window, document);
答案 0 :(得分:0)
这段代码对我来说很奇怪:
$.extend(Plugin.prototype, {
methods: {
//
}
});
除了无原因地使用$.extend
之外(原型没有任何现有的属性可以担心覆盖/扩充),你将所有对象实例的函数放在一个名为{{1的属性中}}
写如下:
methods
这将避免Plugin.prototype = {
init: function () {
functions._addInput.call(this);
},
destroy: function () {
console.log('in public destroy');
this.$el.removeData();
},
testMessage: function () {
console.log('in public testMessage()');
},
inputHandler: function (value) {
functions._inputHandler(value);
}
};
的不必要开销,将您的方法放在原型上 - 就在原型上 - 并使所有实例属性($.extend
等)可用于实例方法(原型中包含的方法)。