Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically adding properties to observable object

Tags:

knockout.js

I have a viewmodel like this,

        function viewModel() {
            this.loadData = function() {
                this.Items().C = 3;
            };

            this.Items = ko.observable({ A: 1});
            this.Items().B = 2;
        }

        var vm = new viewModel();
        ko.applyBindings(vm);
        vm.loadData();

I am printing out the values like this,

        <span data-bind="text: $root.Items().A"></span>
        <span data-bind="text: $root.Items().B"></span>
        <span data-bind="text: $root.Items().C"></span>

It prints out values of A and B, but not C?

Thanks.

like image 927
user471317 Avatar asked Feb 21 '13 18:02

user471317


1 Answers

Since, C itself is not observable initially, the binding would not know that it needs to update when a change is made.

To make it update, you would either need to reset Items entirely:

this.loadData = function() {
    var existing = this.Items();
    existing.C = 3;
    this.Items(existing);
};

or call the valueHasMutated function of the observable, to force any subscribers to update like:

this.loadData = function() {
    this.Items().C = 3;
    this.Items.valueHasMutated();
};
like image 164
RP Niemeyer Avatar answered Sep 20 '22 15:09

RP Niemeyer