Search code examples
javascriptbackbone.js

Uncaught TypeError: this.getKeyCode is not a function


In my backbone view i have a function that calls another function defined in the same view like this:

View.FormCustomer = CommonViews.FormCustomer.extend({
        title : "Ajouter une fiche client",
        events : {
            "keypress  .customerForm" : "getKeyCodeD"
        },
        getKeyCode : function(e) {
            if (e.keyCode == "13") {
                this.save(e);
            }
        },
        getKeyCodeD : function(e) {
            $(document).on('keypress.namespace', function(e) {
                this.getKeyCode(e);
            });
    },

When i invoke the getKeyCodeD function by pressing a key i got an error that says Uncaught TypeError: this.getKeyCode is not a function

I think the $(document).on is the problem because when i invoke the getKeyCode function directly there is no problem in calling this.save(e);

How can i solve this without making $(document).on in the initialize ?


Solution

  • The issue is with scope change. this keyword points to #document during execution, so you should re-bind the scope you want - the backbone class:

    $(document).on('keypress.namespace', function(e) {
        this.getKeyCode(e);
    }).bind( this );
    

    Here is workaround.