0

Hi i have the following field

<span id="myText" data=bind="text: name">default value</span>

I want to be able to initialize the value with like

var model = {
   name = ko.observable("");
}
ko.apply(model);

However, i do not want the value "default value" to change. I want to preserve the original value.

How can i go about doing this?

Chun ping Wang
  • 3,879
  • 12
  • 42
  • 53
  • Preserve it until the value of name is changed? You would need either a computed value, or a special binding that read "default value" until its source was non-empty. There is no way to stop the template from updating the way you are asking. – Kyeotic Nov 05 '12 at 16:59

1 Answers1

1

One option would be to use a custom binding to populate your observable from the element's current innerText.

Something like:

ko.bindingHandlers.textWithInit = {
    init: function(element, valueAccessor) {
        var observable = valueAccessor();
        observable("innerText" in element ? element.innerText : element.textContent);   
    },
    update: ko.bindingHandlers.text.update
};

You could add more error handling to this as well (handle observables & non-obseravbles, etc.)

Sample: http://jsfiddle.net/rniemeyer/x4XJW/

RP Niemeyer
  • 114,592
  • 18
  • 291
  • 211