There is a plugin for jQuery. I hang it on input. At the onkeydown event, the KeyDown method should work. But in response to the console I see this:

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

In writing plugins novice, do not kick much.

 ; (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 answers 2

    The problem is in this case in scope:

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

    this - which is inside the function, it does not refer to the Plugin object. It refers to the item you are working with. To fix this, you need to define the object's instance variable:

     init: function() { var _this = this; this.el.on('keydown', function (e) { _this.KeyDown(e); }); }, 
    • @zhenyab: get ahead a bit :) - Pavel Azanov

    In the anonymous keydown processing keydown , this has nothing to do with your plugin. Accordingly, it does not have a KeyDown method.

    Change:

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

    on:

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