Rogare
Rogare

Reputation: 3274

How to call "class method" from outside class in JavaScript?

I've got some code in JavaScript and I'm looking to trigger a ViewModel method using a keyboard shortcut. What is the correct syntax? Here's my code:

document.addEventListener('keydown', function(event) {
    if (event.keyCode==27){
        ViewModel.escapePressed();
    }
}, true);

function ViewModel() {
    this.escapePressed=function(){
        // Code
    };
}

Upvotes: 0

Views: 10001

Answers (1)

Quentin
Quentin

Reputation: 943097

If you are going to use that style of class, then you must first make an instance of it.

var a_view_model = new ViewModel();
a_view_model.escapePressed();

… but if you just want to have a static method, then you probably shouldn't be using a constructor function in the first place

var view_model = {
    escapePressed: function () { };
}

and:

view_mode.escapePressed();

Upvotes: 4

Related Questions