Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout JS clear function ko.observable

Tags:

knockout.js

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.

like image 545
Ravi Ram Avatar asked Jan 28 '13 18:01

Ravi Ram


People also ask

How do you clear a Knockout observable array?

To clear an observableArray you can set the value equal to an empty array.

What is Ko observable in knockout JS?

Knockout. js defines an important role when we want to detect and respond to changes on one object, we uses the observable. An observable is useful in various scenarios where we are displaying or editing multiple values and require repeated sections of the UI to appear and disappear as items are inserted and deleted.

How do you get the Knockout value from observable?

To read the observable's current value, just call the observable with no parameters. In this example, myViewModel. personName() will return 'Bob' , and myViewModel. personAge() will return 123 .

What does Ko unwrap do?

unwrapObservable(item) Looking at the code, that call basically checks to see if item is an observable. If it is, return the value(), if it's not, just return the value.


2 Answers

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/

like image 85
bikeshedder Avatar answered Oct 23 '22 09:10

bikeshedder


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.
like image 41
Tracker1 Avatar answered Oct 23 '22 10:10

Tracker1