0

Есть плагин для jQuery. Вешаю его на input. При событии onkeydown должен срабатывать метод KeyDown. Но в ответ в консоли вижу такое:

Uncaught TypeError: Object #<HTMLInputElement> has no method 'KeyDown'

В написании плагинов новичок, сильно не пинайте.

; (function ($, window, document, undefined) {

    function Plugin(element, options) {

        var defaults = {
            width: 270,
            height: 300
        };

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

        this.init();
    }

    Plugin.prototype = {

        init: function () {
            this.el.on('keydown', function (e) { this.KeyDown(e); });
        },

        KeyDown: function (e) {
            console.log('Yeah!!!');
        }

    };

    $.fn.myplugin = function (options) {
        return this.each(function () {
            if (!$.data(this, 'plugin_myplugin')) {
                $.data(this, 'plugin_myplugin',
                new Plugin(this, options));
            }
        });
    }
})(jQuery, window, document);

2 ответа 2

2

Проблема состоит в данном случае в scope:

this.el.on('keydown', function (e) { 
      this.KeyDown(e);
});

this - который находится внутри функции, он не относится к объекту Plugin. Он относится к элементу с которым Вы работаете. Чтобы исправить это, нужно определить переменную instance объекта:

init: function() {  
    var _this = this;

    this.el.on('keydown', function (e) {
        _this.KeyDown(e);
    }); 
},
1
  • @zhenyab: опередили немного :) 12 июл 2013 в 8:45
2

В анонимной функции обработки keydown у Вас this уже не имеет отношения к Вашему плагину. Соответственно не имеет метода KeyDown.

Измените:

this.el.on('keydown', function (e) { this.KeyDown(e); });

на:

this.el.on('keydown', this.KeyDown);

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.