0

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

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

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.