igoshev
igoshev

Reputation: 25

JQuery plugin does not work

Plugin for jQuery. Set it on the input.

onkeydown event must call the KeyDown. But in response to the console, I see this:

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

In writing plugins I'm a newbie.

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

Upvotes: 0

Views: 107

Answers (1)

Ren&#233;
Ren&#233;

Reputation: 6176

The this keyword will not work inside the function function (e) { this.KeyDown(e); } because it's overwritten by jQuery. The new this refers to the element.

Try something like:

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

Upvotes: 3

Related Questions