Knockout Part 4: Inputs

Knockout has a few settings specific to inputs.  Knockout has basic value bindings for input types, but also has events and attributes specific to inputs too.  Rather than go through a lengthy explanation, I think it’s best just to jump in and illustrate as we go.  First, we have the following view model:

var viewModel = {
fieldValue: ko.observable(“”),
fieldComment: ko.observable(“”),
clicked: function() {
this.fieldValue(“”);

viewModel.buttonEnabled = ko.computed(function() {
return viewModel.fieldValue().length > 0;
});

ko.applyBindings(viewModel);

This view model is used to populate some inputs in the application; our first input is a textbox:

<input id=”Text” type=”text” value=”” data-bind=”value:fieldValue” />

Notice the value binding, which is specific to binding the value property to an input.  Simple enough; next we have a button, which uses a few more.

<button data-bind=”{ enable:buttonEnabled, click:clicked }”>Submit</button>

Here we have a click event handler callback named clicked (notice clicked in the above view model).  The button also uses a computed observable as a means for enabling and disabling the button.  Knockout will apply this as values in the view model change.  Conversely, Knockout has a disable binding for the opposite effect.

Input bindings are simple enough, and provide input-specific actions (handling clicks and enabling/disabling) for your views.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s