Knockout Part 3: Events

Knockout supports an eventing structure that can tie a function to an element through a binding statement.  While in JQuery, a developer may attach to an element’s event through this:

$(“#btn”).click(function() { .. });

In knockout we can also support this functionality by defining an event handler using a declarative statement:

<input type=”button” data-bind=”click:clickHandler” />

This requires defining in our view model a method:

function viewModel() {
var self = this;

self.clickHandler = function() { .. };

Knockout links methods in the model to the event, and supports click and submit out of the box.  If you want to attach to any other event, an event binding allows you to customize the method name, as in the following code sample.  This assumes mover and mout are methods in the view model.

<div data-bind=”event:  mouseover: mover, mouseout: mout”></div>

Events, depending on the type, may accept an argument.  The submit binding passes in a reference to the form element, and accepts a boolean value as the result.  If true, the form posts back as normal; if false, post back is blocked. The click handler can use an empty method, but can also take two references, one for the data object, and another object specific to the event raised.

Another feature with events is scoping; scoping means that we can use the $parent, $parents, or $root references (referenced in the previous blog post) to refer to an event handler at that particular scope (like  data-bind=”$root.mover”; using $root, we can directly refer to a handler in the view model, when the scope has changed).

Everything illustrated thus far used a method as the event handler; code can also be entered in line, as in the following example too.

<button data-bind=”click: function(data, event) { .. }”>Save</button>

In all of these examples, we defined a way to attach to events outside of the normal JavaScript/JQuery structure that developers are used to, and I hope you can see how powerful that events can be within the Knockout framework.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s