Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockoutJS, event is triggered, however event.which still undefined

here's my code.

    <input type="text" placeholder="Add New Tag" data-bind="value: tagToAdd, valueUpdate: 'afterkeydown', event: { keypress: addOnEnter }" />

here's my knockout code.

    self.addOnEnter = function (event) {

        console.log(event.which);

        var keyCode = (event.which ? event.which : event.keyCode);
        if (keyCode === 13) {
            self.addTag();
        }
        return true;
    };

when I type something in the input field, then I log the event, kept getting undefined back. I dont know why I cannot catch which event is fired.

you can test my code on jsFiddle. http://jsfiddle.net/GBLNR/6/

just type anything in the input field, then watch the result from the console.

like image 230
qinking126 Avatar asked Dec 15 '25 17:12

qinking126


1 Answers

Knockout passes the current data context as the first argument to a handler. The event is the second argument.

So, the signature for your function needs to be:

self.addOnEnter = function(data, event) {

}

Alternatively, a good way to handle this is through a custom binding like:

//a custom binding to handle the enter key (could go in a separate library)
ko.bindingHandlers.enterKey = {
    init:function (element, valueAccessor, allBindingsAccessor, data, context) {
        var wrappedHandler, newValueAccessor;

        //wrap the handler with a check for the enter key
        wrappedHandler = function (data, event) {
            if (event.keyCode === 13) {
                valueAccessor().call(this, data, event);
            }
        };

        //create a valueAccessor with the options that we would want to pass to the event binding
        newValueAccessor = function () {
            return { keyup:wrappedHandler };
        };

        //call the real event binding's init function
        ko.bindingHandlers.event.init(element, newValueAccessor, allBindingsAccessor, data, context);
    }
};

Now you would just use this enterKey binding against your addOnEnter function and it woul d only need to deal with your data.

like image 167
RP Niemeyer Avatar answered Dec 17 '25 07:12

RP Niemeyer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!