Search code examples
knockout.jsknockout-postbox

Knockout array being displayed as a function, not the contents


I have the following:

this.testArray = ko.observableArray(["a", "b"]);
this.publishedSelectedSets = ko.observableArray().subscribeTo("SELECTED_SETS");

Then in my view I have:

<span data-bind="text: testArray "></span>
<span data-bind="text: publishedSelectedSets "></span>

I'd expect to see a,b and then a list of the contents of publishedSelectedSets (just numbers), but what gets displayed is:

SELECTED SET IDS: a,b

function observable() { if (arguments.length > 0) { // Write // Ignore writes if the value hasn't changed if ((!observable['equalityComparer']) || !observable['equalityComparer'](_latestValue, arguments[0])) { observable.valueWillMutate(); _latestValue = arguments[0]; if (DEBUG) observable._latestValue = _latestValue; observable.valueHasMutated(); } return this; // Permits chained assignments } else { // Read ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation return _latestValue; } }

I tried adding parentheses at the end of publishedSelectedSets() but I get the same thing. I can use the debugger to see _latestValue updating correctly for the publishedSelectedSets array, but the data isn't displaying correctly in the DOM.

What am I doing wrong?

SELECTED_SETS:

this.selectedSets = ko.computed(

    function () {
        return ko.utils.arrayMap(ko.utils.arrayFilter(vm.data.sets(), function (set) {
            return set.isSelected();
        }), function (set) { return set.setId; });

    }).publishOn("SELECTED_SETS");

JSFiddle which is working, with a simplified use of ko.utils.arrayMap: http://jsfiddle.net/PTSkR/80/

Still can't figure out why my code isn't working...


Solution

  • Your publishedSelectedSets array contains ko.observable functions that is why you get the strange output.

    And you have observable functions in your array because of your map method:

    function (set) { return set.setId; }
    

    Where you are returning the observable function itself with the set.setId and not its value.

    To fix it just put out the ()

    function (set) { return set.setId(); }