Nathan Friend
Nathan Friend

Reputation: 12804

Returning true doesn't allow default action in Knockout "event" binding

According to the Knockout docs for the "event" binding:

By default, Knockout will prevent the event from taking any default action.

....

However, if you do want to let the default action proceed, just return true from your event handler function.

This doesn't seem to be working for me. Here's my view:

<input data-bind="event: { 'keydown': function(d, e) { onInputKeydown(e); } }" />

and the event handler in my ViewModel:

onInputKeydown = function(e) {
    console.log(e.which);
    return true;
}

This handler is preventing any characters from being entered into the <input> element. What am I doing wrong?

Upvotes: 2

Views: 931

Answers (3)

Paul Franke
Paul Franke

Reputation: 649

I think the issue is how you bind the function. Please try the following instead:

    <input data-bind="event: { keydown: onInputKeydown }" />

Knockout will pass the parameter data and event to your function.

    onInputKeydown = function(data, event) {
       console.log(event.which);
       return true;
    }

Upvotes: 1

Jonathan Eckman
Jonathan Eckman

Reputation: 2077

Yes it is true that you need to return true from your function. I also found that if I hit a breakpoint in my function, the keydown event seems to ignore that I had returned true. Disable all breakpoints and it works fine.

Upvotes: 0

Nathan Friend
Nathan Friend

Reputation: 12804

The function in your ViewModel is indeed returning true, but the wrapper that you specify in your view isn't propagating the return value of that function. Try this (note the addition of return):

<input data-bind="event: { 'keydown': function(d, e) { return onInputKeydown(e); } }" />

Upvotes: 2

Related Questions