Tuesday, April 16, 2013

Conditional event binding in KnockoutJs

Conditional event binding in KnockoutJs. Bind events : onclick,onblur,mouseout,hover based on condition (if)in knockoutJs.


Most of the time it is required to call different methods on client side based on condition. like RequireValidation is true then call function ValidateForm but if RequireValidation is false then call function SubmitFrom. this is very simple in server-side controls but in frameworks like MVC, most of the things are to be done in client scripts is bit difficult, specially when using KnockoutJs.

For fixing the same many of us uses different button (multiple button with same text) and show/hide then as per condition.
But this increases the content in HTML and make it difficult for review.
Here is the simple example to attach onblur event with a textbox as 

-- HTML --


<input type="text" data-bind="attr: { onclick: itemSelected() ? 'alert(\'tt\')' : 'alert(\'ff\')' }" />



-- JavaScript --


function viewModel() {
    this.itemSelected = ko.observable(false);
}
ko.applyBindings(new viewModel());

0 comments:

Post a Comment