Ravi Ram
Ravi Ram

Reputation: 24488

Knockout JS clear function ko.observable

I would like to remove/clear a field of its bindings.

self.Selected = ko.observable();

"Selected": {
    "ID": 5,
    "Name": "22",
    "Active": true,
    "Temp": "2013-01-28T18:14:48.340Z"
  }

self.Selected.remove() --- > error: has no method 'remove'

self.Selected.removeAll(); --> Cannot call method 'removeAll' of undefined

self.Selected.cleanNode()--- > error: has no method 'cleanNode'

http://jsfiddle.net/yvTFN/24/ : so you can see a working example

After you EDIT a name, the self.update = function will do work, then should clear the property Selected, otherwise, if you click update again (no value), the value will update with empty string.

Upvotes: 10

Views: 25351

Answers (2)

bikeshedder
bikeshedder

Reputation: 7487

Just set the value of Selected to null:

self.Selected(null);

Edit: Your jsfiddle is using ko.removeNode which does not what you want.

For a working version see: http://jsfiddle.net/yvTFN/26/

Upvotes: 19

Tracker1
Tracker1

Reputation: 19344

self.Selected.clearBindings = function __clearSelection__() {
    self.Selected = new ko.observable(self.Selected());
    self.Selected.clearBindings = __clearSelection__;
}

This approach may do what you need, depending on what it is you really need... There are some caveats

  • I don't know the internals of KnockoutJS
  • There will probably be memory leaks in some browsers (IE<9)
  • If this is a long-running page, and this method called many times, you may have unexpected results.

Upvotes: 1

Related Questions