Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

idiom for comparing knockout observables

Tags:

knockout.js

I have the following problem. I want to check that the item clicked on in table is not the same as model.selected.

var model= {
items:  ko.observableArray(),
selected : ko.observable()
};

<tbody>
<!-- ko foreach: model.items -->
<tr data-bind="click:$parent.model.set_selected_item">
<td style="cursor:pointer" data-bind="varchar : title"></td>
</tr>
<!-- /ko -->
</tbody>

//ID is an observable
//selected may not be set yet - i.e an empty observable;



 var set_selected_item = function(item){
    //if item is different set 
      model.LandItem_selected(item);
      do_routine(item)
    //else
      //do nothing
    }

because the item is an observable is is never null; how would I check if the observable has not been set yet?

Any help much appreciated.

like image 362
Chin Avatar asked Jan 18 '23 03:01

Chin


2 Answers

Unwrap observable before comparing

var item1 = ko.observable()
console.log(ko.utils.unwrapObservable(item1))
console.log(ko.utils.unwrapObservable(item1) == null)
item1(1)
console.log(ko.utils.unwrapObservable(item1) == null)

output

undefined

true

false

like image 138
Artem Avatar answered Jan 25 '23 23:01

Artem


You could use open up the observable by using parentheses, like this:

var underlyingValue = item();

or, if you are uncertain if the variable is an observable you can use this method:

var underlyingValue = ko.utils.unwrapObservable(item);

which basically checks whether the variable is an observable or not and if it is, it does the first this with the parentheses.

When you have the underlying value you can do what you normally would do.

like image 45
Mikael Östberg Avatar answered Jan 25 '23 22:01

Mikael Östberg