简体   繁体   中英

Unexpected behaviour with KnockoutJS Keypress event on input

I have an event binding on an input of type search, this is in order to fire a search off to the server side and populate the list as the user is typing.

That part is fine and I have established a skeleton example using pure javascript, when it came time to integrate into knockout, I ran into a curious issue.

I have in my HTML the standard binding:

<input data-bind="event:{keypress:ring}" type="text" />

For this example my ring function will simple log something when the key is pressed :

ring: function (event) {
            this.triggered(this.triggered() + 1);
            var msg = "Keypress binding called " + this.triggered() + " time(s).";
                    console.log(msg);
                } 

That's all normal and no problem with that..

The problem is the input value/string is not being updated.. It simply stays blank as if I have not pressed anything.

Im curious am I missing some sort of default forwarding I am supposed to do ? Is this expected behaviour ? Seems a little strange to me.

A working example is here : JSfiddle

As you type into the input, nothing happens apart from my ring function.

You need to return true from your event handler function to allow the default action to take place on the input.

Demo here: http://jsfiddle.net/szcuyq13/1/

    ring: function (event) {
        this.triggered(this.triggered() + 1);
        var msg = "Keypress binding called " + this.triggered() + " time(s).";
        console.log(msg);
        return true;
    } 

In other words, this is exactly as you guessed: you just need to add a little bit more to ensure the 'default forwarding' happens as you expect. KO by default prevents the default action in a bound event handler and by returning true you are requesting that default action to complete. It's described here, under the heading Note 3:

http://knockoutjs.com/documentation/event-binding.html

That note also explains why KO does this, which makes sense when you think of it with anchors and clicks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM