Search code examples
knockout.jsko.observablearray

What's the correct way to assign an element by index to a knockout.js observableArray?


I've been looking at the documentation for knockout's observableArray, and I'm having trouble figuring out how to do one of the most fundamental things you can do with an array: assign a value by index.

Things I've tried: (given oa = ko.observableArray([1,2,3]))

  • oa(1, 10);
  • oa[1] = 10;
  • oa()[1] = 10;
  • oa.splice(1, 1, 10);

The last one seems work, but I'm concerned that .splice() might be inefficient since it has to be concerned with shifting all the subsequent values. I'd prefer to just do simple index-based assignment.

I've created a jsfiddle that shows an observableArray being weird.

<ol data-bind="foreach: list">
    <li data-bind="text: $data"></li>
</ol>

<script>
    var model = {
        list: ko.observableArray([3, 5, 7])
    };

    ko.applyBindings(model);

    setTimeout(function() {
        model.list()[1] = 55;
        model.list.push(99);
        model.list()[2] = 77;
    }, 2000);
</script>

Solution

  • Apply valueHasMutated property on your observable after modification

    setTimeout(function() {
        model.list()[1] = 55;
        model.list.push(99);
        model.list()[2] = 77;
        model.list.valueHasMutated();
    }, 2000);