KnockoutJS–Event binding

4 בדצמבר 2011

one comment

KnockoutJS–Event binding


After binding the data into our page, we wish to be able to create an interactive page. This means that we want to be able to add some behavior to our view-model, triggered by an event on the page. (A button being clicked for example).

The click binding

You can bind to the click binding the same as you bind to the value only that now it’s expects a parameter-less function. In case you have a method that expect parameters you can have a binding expression like that:

 <button data-bind="click: function() {viewModel.setSelectedCustomer(yourParameter)}">Set customer </button>

On that binding you’re operating a function on your view-model triggered by the button click.

The click binding is not restricted to buttons of course, you can triggered event for every clickable HTML element.

The event binding

If you wish to bind to another events such as mouseover, keypress etc. you need an event-binding. It’s syntax is slightly different but there isn’t a big change.

All events you wish to bind are to be kept inside one block ({event1: handler, event2: handler }) every handler is a parameter-less function however you can bind to an expression the same as the click binding above.

See below, example for event binding with mouseover and mouseout:

<input type="text" 

data-bind="value: channelUrl, event: {mouseover: function() {viewModel.title('Get Items')}, mouseout : function() {viewModel.title('')}}" />


In order to add interactivity to our page (otherwise it won’t be an application) we need to bind events to functions on our view-model. The function expected to be bound are ones without parameters however we can bind to an expression by having the event name, followed by the function() keyword and then, our Javascript expression.

When the event is fired, the bounded function on our view-model will execute. On that function we ought to change another bounded data, call server side by AJAX and so on.

kick it on

Add comment
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. (*) שדות חובה מסומנים

תגי HTML מותרים: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

one comment

  1. CLELUTTTRETTY5 בפברואר 2013 ב 4:45

    Oh my goodness! an amazing article dude. Thank you On the other hand I'm experiencing concern with ur rss . Don't know why Unable to subscribe to it. Is there any individual acquiring identical rss challenge? Any person who knows kindly respond. Thnkx

    []Personalized NFL Jerseys[/url]