简体   繁体   中英

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()) }" />

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.

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 (ie it doesn't know how to call the observable function to set the value).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM