Question

I am working with binding a json data in a ul tag. It shows that an error has occured .Here is the code:

<div id="newdiv" data-bind="visible: selectedSection() === 'ulClass', stopBinding: true ">
    <ul id="ulClass" data-bind="template: { name: 'templatesSample', foreach: items}">
        <script id="templatesSample" type="text/html">
            <li><span data - bind = "text:name" > </span>
            </li>
        </script>
    </ul>
</div>

The view model

function names(firstnames) {
    this.name = ko.observable(firstnames);
}

var mappedData;
var viewmodel;

$(document).ready(function () {
    ko.bindingHandlers.stopBinding = {
        init: function () {
            return {
                controlsDescendantBindings: true
            };
        }
    };
    ko.virtualElements.allowedBindings.stopBinding = true;

    viewmodel = function () {
        items: ko.observableArray([]);
    };


    var namesOfPeople = '[{"Firstnames":"john"},{"Firstnames":"peter"},{"Firstnames":"mary"}]';
    var dataFromServer = ko.utils.parseJson(namesOfPeople);
    mappedData = ko.utils.arrayMap(dataFromServer, function (item) {
        return new names(item.Firstnames);
    });

    viewmodel.items(mappedData);

    ko.applyBindings(viewmodel, document.getElementById("ulClass"));
});

It shows following error in the console:

Uncaught TypeError: Object function ()
    {
         items:ko.observableArray([]);

    } has no method 'items' 

How can I fix the problem?Please suggest a solution.

Thanks

Was it helpful?

Solution

You need to decide between initializing your vm as an object, or with a constructor function.

This is a combination of both, mostly sintactically invalid I think :):

viewmodel = function()
{
    items:ko.observableArray([]);
};

So either do this:

viewmodel = {
                items:ko.observableArray([]);
            };

Or this:

var VM=function() {
                     this.items = ko.observableArray([]);
                };

var viewModel = new VM();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top