0
我們正在改變我們的核心jQuery插件模板。下面是一個模擬樣本。我遇到的問題是:jQuery插件 - 如何在原型中訪問this.el
- 我宣佈this.el這$ EL在關閉插件
- 然而,我需要爲了獲得每一種原型將它傳遞給了。私人功能。
我們如何獲得這是在封閉的插件?
;(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);
@JAAudle。我知道這是一個愚蠢的錯誤。這種結構從另一種佈局結轉。完美的作品。感謝您指點 – TonyaGM 2014-10-16 23:39:17
沒問題,我懷疑它是從另一個範例中擱置。 :) – JAAulde 2014-10-16 23:40:18