Skip to content

Instantly share code, notes, and snippets.

@SteveSanderson
Created May 3, 2012 08:32
Show Gist options
  • Save SteveSanderson/2584398 to your computer and use it in GitHub Desktop.
Save SteveSanderson/2584398 to your computer and use it in GitHub Desktop.
Sample step

##Making the data editable

You're not limited to displaying static data. Let's use the value binding, along with some regular HTML <input> controls, to make the data editable.

Add the following markup to the bottom of your view (leaving the existing markup in place above it):

<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>

Now run the application. What happens when you edit the text in one of the text boxes?

Hmm... apparently nothing happens. Let's fix that...

###Introducing Observables

Actually, when you edit one of those text boxes, it does update the underlying viewmodel data. But because the viewmodel properties are just plain JavaScript strings, they have no way of notifying anybody that they've changed, so the UI stays static. That's why Knockout has a concept of observables - these are properties that automatically will issue notifications whenever their value changes.

Update your viewmodel to make the firstName and lastName properties observable using ko.observable:

function AppViewModel() {
    this.firstName = {*ko.observable("Bert")*};
    this.lastName = {*ko.observable("Bertington")*};
}

Now re-run the application and edit the text boxes. This time you'll see not only that the underlying viewmodel data is being updated when you edit, but that all associated UI is updating in sync with it too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment