admin管理员组

文章数量:1389749

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
    };
}

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
    };
}
Share Improve this question asked Nov 20, 2015 at 23:15 RogareRogare 3,2744 gold badges30 silver badges54 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

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

本文标签: How to call quotclass methodquot from outside class in JavaScriptStack Overflow