KnockoutJS - 创建对象不起作用

时间:2013-10-20 15:51:08

标签: javascript asp.net-mvc-4 knockout.js

我正在使用菜单和子菜单进行导航列表。

我有以下结构:

function Menu(navigation) {

    this.NavigationUrl = ko.observable(navigation.NavigationUrl);
    this.NavigationTitle = ko.observable(navigation.NavigationTitle);
    this.NavigationDescription = ko.observable(navigation.NavigationDescription);

    var mappedChildren = ko.utils.arrayMap(navigation.Children, function (child) {
        return new Menu(child);
    });

    this.Children = ko.observableArray(mappedChildren);
}

function DashboardViewModel() {

    var self = this;
    self.LoggedUser = ko.observable("");
    self.Navigations = ko.observableArray([]);

    $.get('/Home/DashboardDependencies', {}, function (result) {

        self.LoggedUser(result.LoggedUser);

        var mappedNavigations = ko.utils.arrayMap(result.Navigations, function (item) {
            var menu = new Menu(item);

            // When I alert item, the result appears properly:
            // { "NavigationTitle": "blah", "NavigationDescription": "bleh" [...] }
            alert(JSON.stringify(item));

            // But when I alert the new menu object, the result doesn't appear:
            // Just: "{}"
            alert(JSON.stringify(menu));

            return menu;
        });
        self.Navigations = mappedNavigations;
    });
}

ko.applyBindings(new DashboardViewModel());

所以,看看吧。当我尝试提醒项目变量时,结果显示正确。当我尝试提醒新的Menu对象时,结果只显示{}。为什么会这样?

谢谢大家的帮助!

1 个答案:

答案 0 :(得分:0)

self.Navigations = .. 更新现有的observable数组。因此,视图绑定的可观察数组永远不会更新,并且视图永远不会更新。

改为使用self.Navigations(..)