Nan Li
Nan Li

Reputation: 593

In KnockoutJs how to subscribe to a value which is null initially?

<select data-bind="options: SelectedCountry() ? SelectedCountry().Cities : '',
optionsText: 'Name', value: SelectedCity, optionsCaption: '-- Select a City --'"></select>

I want to subscribe to SelectedCity

$(function ()
{
  vm.SelectedCity.subscribe(function ...

Knockout throws an error "Unable to get property 'subscribe' of undefined or null reference"

Of cause when the page loads, SelectedCity is still null, so how do I subscribe to it?

I'm using knockout mapping,

var vm = ko.viewmodel.fromModel(JSON.parse(vmJs));
ko.applyBindings(vm);

vmJs is generated at the server, and I can see ..."SelectedCity":null,... inside vmJs.

Upvotes: 0

Views: 869

Answers (1)

Nan Li
Nan Li

Reputation: 593

I didn't realize I made a mistake. I wrote

vm.SelectedCity().subscribe

instead of

vm.SelectedCity.subscribe

in my code. so there is no issue, an observable can be subscribed even if the initial value is null.

Upvotes: 1

Related Questions