I have this plugin with the structure of boilerplate. My problem is to create the event ‘controlEventoKeyUp’.
Be able to access the methods of the plugin, I had to ignore the plugin parameter bind('keyup',_{_plugin:_this_},_controlEventoKeyUp).
This solved my problem but I found a tidy way of doing this.
Can another solution there be with this model?
(function ($, window, document, undefined) {
var pluginName = 'controlLenInput',
defaults = {
maxLen: 100,
displanCantidadActual: null,
textUppercase: false
};
// The actual plugin constructor
function Plugin(element, options) {
this.element = element;
this.options = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
};
Plugin.prototype.init = function () {
$(this.element)
.bind('keyup', { plugin: this }, controlEventoKeyUp)
.trigger('keyup');
};
Plugin.prototype.asignarValorActual = function () {
$(this.options.displanCantidadActual)
.html('<span>' + (this.options.maxLen - $(this.element).val().length) + '</span> <span>caracteres pendientes</span>');
};
var controlEventoKeyUp = function (event) {
var _plugin = event.data.plugin;
if (_plugin.options.maxLen < $(this).val().length) {
$(this).val($(this).val().substr(0, _plugin.options.maxLen));
}
else {
_plugin.asignarValorActual();
}
if (_plugin.options.textUppercase) {
$(this).val($(this).val().toUpperCase());
}
};
$.fn[pluginName] = function (options) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName, new Plugin(this, options));
}
});
}
})(jQuery, window, document);
After looking over the boilerplate template, I could see that calling plugin, is recorded in “data” the instance of the plugin:
then, to retrieve the instance of the plugin for this element, simply, in the event, I get back it this way:
so then would be the function of the event:
Edit
As fires a “trigger” event, when I access the plugin with “$. data” creates an error, because it still is not there already.
change so as to keep the plugin. in this way, I can access the plugin already loaded without error.