onEnter Event binder for knockoutJs

It is generally required to trigger an event when user press enter in the text box. Well this is very much simpler as, bind keydown event of jquery and check for keycode 13 that is if enter is pressed. But this is not valid in big application as it is generally required to build some framework or generic method / custom event to track the same along with other functionality. so here we are building a binding handler for the same to segregate common events as

-- Binding Handler--


ko.bindingHandlers.onEnter = {
    init: function(element, valueAccessor, _, viewModel) {
        ko.utils.registerEventHandler(element, 'keydown', function(evt) {
            if (evt.keyCode === 13)
                valueAccessor().call(viewModel);
        });
    }
}

add the above binding handler and thats done. now anyone can bind onEnter event in their control very easily, to use it see the sample beloy.

-- HTML --


<input type="text" data-bind="                                                                             
hasfocus: edit,
value: title,
onEnter: stopEdit" />
<p data-bind="text: title"></p>



-- Complete JavaScript Block --


ko.bindingHandlers.onEnter = {
    init: function(element, valueAccessor, _, viewModel) {
        ko.utils.registerEventHandler(element, 'keydown', function(evt) {
            if (evt.keyCode === 13)
                valueAccessor().call(viewModel);
        });
    }
}
function ViewModel() {
    this.title = ko.observable("default value");
    this.edit = ko.observable(false);
    this.stopEdit = function() {
        this.edit(false);
        
        // If the edit update is in a timeout, then it works
        // var edit = this.edit;
        // setTimeout(function() { edit(false); }, 0);
    };
}
    
ko.applyBindings(new ViewModel());


author

I love to learn new technologies and passionated for building things. At my daily job, I am a Senior Software Engineer and Member of Architecture Group at Nagarro, building software for the enterprise on the Microsoft stack. In my spare time, I loves hacking on random ideas or innovative solutions.

Comments

  1. this is good to have feature, otherwise can be handled easily.

Leave a Reply