Wednesday, April 17, 2013

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());

0 comments:

Post a Comment