Yuwaz
Yuwaz

Reputation: 413

How to call the knockout.js event from the keyDown event

I want to execute the event bound by knockoutjs from the keyDown event.

Html

<button id="copyButton" data-bind="click: clipboardModel.copy">copy</button>

jQuery

$('#someElement').on('keydown', function(e) {
    switch (e.keyCode) {
        case 67: // c
            if (!(e.ctrlKey || e.metaKey)) break;
            $('#copyButton').click();
            break;
    }
});

It works with this, but not seems to be the right way.

Upvotes: 0

Views: 347

Answers (1)

James Thorpe
James Thorpe

Reputation: 32192

You can bind to the event directly:

<input id="someElement" data-bind="event: { keydown: clipboardModel.copyKeydown }" />

Though it does mean you'll need to put your keyCode check in the knockout function instead:

var clipboardModel = {
    copyKeydown: function(data, e) {
        switch (e.keyCode) {
            case 67: // c
                if (!(e.ctrlKey || e.metaKey)) break;
                clipboardModel.copy();
                break;
        }
    },
    copy: function() { /*...*/ }
}

I've made some assumptions to your viewmodel here, you may need to adapt this slightly.

Upvotes: 1

Related Questions