0

I have this viewmodel and a function to add data to it,

        function viewModel() {
            this.loadData = function() {
                this.Items().push('X');
                this.Items().push('Y');
            };

            this.Items = ko.observableArray(['A', 'B']);
        }

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

I am trying to print out the values in Items array, but X and Y are never displayed. Though the alert pops up A, B, X, and Y. What am I doing wrong?

    <div data-bind="foreach: {data: Items, as: 'item' }">
        <span data-bind="text: item"></span>
    </div>          

Thanks.

2 Answers 2

1

this.Items() exposes the underlying array of ko.observableArray(), which is just a normal array. You need to use this:

this.Items.push('X');
this.Items.push('Y');

demo

Sign up to request clarification or add additional context in comments.

2 Comments

I am a little confused on when to use this.Items and when to use this.Items()? I thought I should always use Items() - I posted a similar question yesterday, stackoverflow.com/questions/14992898/…
Use this.Items when you want the KnockOut 'magic' to happen when you change the contents of the array (this.Items looks like an array, but isn't really; it's a special KnockOut type which mimics an array; this.Items() returns the actual array where the data is stored, but it's not 'magic'). Your other question uses an observable, not an observableArray, which are two different things.
0

You should push the data directly to this.Items.

this.Items() returns the content of the observableArray.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.