Adam Rackis
Adam Rackis

Reputation: 83358

KnockoutJS - Bind only the initial value

Is there a clean way to bind only the initial value of an observable to a dom element using KnockoutJS?

I know you can achieve this by binding to a non-observable, but I'd rather not create a superfluous property just to hold the initial value of another observable property.

I tried this, but to no avail—the attribute is still updated with every change

<input type="text" id="tbName" 
  data-bind="value:name, attr: { 'data-initialnamevalue': ko.utils.unwrapObservable($data.name()) }" />

Upvotes: 0

Views: 254

Answers (2)

Garry English
Garry English

Reputation: 5200

You can bind directly to the observable value and not the observable by adding the parentheses so that the value is injected when it is first bound. When the element is updated, it will not update the observable because the binding is on the value and not the observable (i.e it doesn't know how to call the observable function to set the value).

<input type="text" id="tbName" data-bind="value: name()" />

Upvotes: 0

Matt Burland
Matt Burland

Reputation: 45135

While I agree with Zero21xxx above, I guess you could use a custom binding where you provide an init method, but no update method.

Not sure it's worth the effort versus just adding another property.

Here's a simple example of what I mean: http://jsfiddle.net/ZkFRu/3/

The first paragraph binds the current value of a property, the second binds the initial value. Clicking the button increments the property.

Upvotes: 1

Related Questions