将数据添加到嵌套的viewmodel?

时间:2013-06-12 00:35:22

标签: mvvm knockout.js

鉴于这个小提琴,如何使用dummyResults正确填充searchResult,使用dummyItems正确填充visibleItem?

http://jsfiddle.net/scottbeeson/SRUKN/

var dummyResults = [
    { name: "Server1", type: "Server" },
    { name: "Server2", type: "Server" },
    { name: "Server3", type: "Server" },
    { name: "App1", type: "Application" },
    { name: "App2", type: "Application" },
    { name: "App3", type: "Application" }
]
var dummyItems = [
    { name: "Server1", type: "Server" }
]

function visibleItem() {
    var self = this;
    this.name = ko.observable("");
    this.type = ko.observable("");
    this.description = ko.observable("");
}

function searchResult() {
    var self = this;
    this.name = ko.observable("");
    this.type = ko.observable("");
}


var viewModel = {
    searchResult: searchResult(),
    visibleItem: visibleItem(),
    showItem: function (item) {
        visibleItems.push(item);
    }
}

$(document).function() {
    ko.mapping.fromJS(dummyResults, searchResult);
    ko.mapping.fromJS(dummyItems, visibleItem);
    ko.applyBindings(viewModel);
    tmp = ko.toJS(viewModel);
}

1 个答案:

答案 0 :(得分:1)

这是你的简化html的小提琴a working edit

var viewModel = {
    searchResult: ko.observableArray(ko.utils.arrayMap(dummyResults, function (item) {
        return new SearchResult(item);
    })),
    visibleItem: ko.observableArray(ko.utils.arrayMap(dummyItems, function (item) {
        return new VisibleItem(item);
    })),
    showItem: function (item) {
        visibleItems.push(item);
    }
};