2012-01-03 1 views
1

У меня есть этот плагин со структурой шаблона. Моя проблема - создать событие «controlEventoKeyUp». Уметь получить доступ к методам плагина, мне пришлось игнорировать параметр плагина bind('keyup',_{_plugin:_this_},_controlEventoKeyUp). Это решило мою проблему, но я нашел аккуратный способ сделать это.Контекст (это) в случае в составе шаблона

Может ли другое решение быть с этой моделью?

(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>&nbsp;<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); 

ответ

0

После просмотра шаблона шаблонного, я мог видеть, что вызов плагина, записывается в «данных» экземпляр плагина:

$.data(this, 'plugin_' + pluginName, new Plugin(this, options)); 

затем, чтобы получить экземпляр плагина для этот элемент, просто, в случае, я вернусь это так:

var plugin = $.data(this, 'plugin_' + pluginName); 

так, то будет функция события:

var controlEventoKeyUp = function (event) { 

    var _plugin = $.data(this, 'plugin_' + pluginName); 

    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()); 
    } 

} 

Редактировать

Как выстреливает "триггер" событие, когда я достигаю плагин «$. data "создает ошибку, потому что ее еще нет. изменить, чтобы сохранить плагин. Таким образом, я могу получить доступ к плагину, который уже загружен без ошибок.

// The actual plugin constructor 
function Plugin(element, options) { 

    this.element = element; 

    this.options = $.extend({}, defaults, options); 

    this._defaults = defaults; 
    this._name = pluginName; 

    this.element['plugin_' + pluginName] = this; 
    this.init(); 
}; 

//... 

var controlEventoKeyUp = function (event) { 

    var _plugin = this['plugin_' + pluginName]; 

    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()); 
    } 

} 
Смежные вопросы