Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

In this view model I'm binding a drop down list with objects. when I want to clear the items from the drop downlist, I've provided selected item with "null" but it does clear the drop down but doesn't remove the selected Item. please see the fiddle. http://jsfiddle.net/aroor/Su8Zq/36/

<select data-bind="optionsCaption: ' ', options: stations, optionsText : 'name' ,value: selectedStation">   </select>
   <button data-bind="click: clearSelectedStation">Clear</button>
     <br>   
      <span data-bind='text : selectedStation().name'></span>



var ClearSelectionViewModel = function () {
    var self = this;

    self.station= ko.observable();
    self.selectedStation = ko.observable();



    self.stations = ko.observableArray([{name :'CLT'},{ name : 'PHL'},{ name :'PHX'},{ name :'PIT'}]);

    self.clearSelectedStation = function () {
    self.selectedStation(null);
   };
   };

 ko.applyBindings(new ClearSelectionViewModel());
share
add comment

1 Answer

up vote 2 down vote accepted

Your binding of

<span data-bind='text : selectedStation().name'></span>

is throwing an error when selectedStation is null. The binding tries to find the .name property of the value returned from selectedStation(), but "null" has no .name property. There are a couple ways to address this:

Wrap your binding in a "with" binding which will protect you from nulls,

<!-- ko with : selectedStation -->
    <span data-bind="text: name"></span>
<!-- /ko -->

or create a computed on your view model to handle the null

var ClearSelectionViewModel = function () {
    var self = this;
    ...
    self.selectedStationName = ko.computed(function(){
        return self.selectedStation() ? self.selectedStation().name : '';
    }
    ....
}

<span data-bind="text: selectedStationName"></span>

or use an If/IfNot binding to handle the null-case.

You can read a bit more about these on my blog.

I hope that helps!

share
    
Thanks Ryan, I read your blogs. It was really helpful. –  ASN Jun 10 '13 at 11:46
add comment

This site is currently not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .