开发者

Getting "variable is not defined" in my Knockout code

I don't understand why the code below keeps throwing a "viewModel is undefined" error, does anyone know why?

I actually think this may be a problem with KnockoutJS, it wants the viewModel to be a property of window. It does not recognise it when it is part of a custom namespace it seems, given that as window.viewModel it works fine! This is my assumption from the tests I have ran. Here is what I am doing:

var myNamespace.fieldworker = {};

myNamespace.fieldworker.GetFields = function() {
    var viewModel = {
        people: [
        new person("Annabelle", ["Arnie", "Anders", "Apple"]),
        new person("Bertie", ["Boutros-Boutros", "B开发者_JAVA技巧rianna", "Barbie", "Bee-bop"]),
        new person("Charles", ["Cayenne", "Cleopatra"])
    ],
        showRenderTimes: ko.observable(false)
    };

    ko.applyBindings(viewModel);
}

Document.ready is invoked from a ui page (html) which goes and calls this function:

function Initialize(url) {
    udfurl = url;
    myNamespace.fieldworker.GetFields();
}

My view is working correctly, with all the stuff I need so there is no problem there, but I cannot figure out the above problem. Any help would be appreciated.


Knockout works fine with passing it any object for the viewModel (does not have to have global scope). However, it sounds like you likely have an element with a data-bind that references the viewModel variable directly rather than a child of it.

Here is a sample that won't work:

<ul data-bind="template: { name: 'itemTmpl', foreach: items}"></ul>

<script id="itemTmpl", type="text/html">
    <li>
        <span data-bind="text: name"></span>
        <button data-bind="click: function() { viewModel.removeItem($data); }">Delete</button>
    </li>
</script>


$(function() {
    var viewModel = {
        items: ko.observableArray([{
            name: "Bob"},
        {
            name: "Sue"}]),
        addItem: function() {
            this.items.push({
                name: "New"
            });
        },
        removeItem: function(item) {
            this.items.remove(item);
        }
    };

    ko.applyBindings(viewModel);
});

So, in this case the viewModel variable does not have global scope, because it is defined in the jQuery ready function. When, we try to use viewModel.removeItem inside the item template, then it will not work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜