0

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

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Or put it on the prototype without instantiating a new object, and calling off the prototype. Not sure his use case, but agreed on not using a constructor for this though, just throwing another idea out there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.