0

我有以下代码:

// viewModel
var cardViewModel = function (data) {
    var self = this;
    ko.mapping.fromJS(data, {}, self);
    self.isNew = ko.observable(false);
    // etc
}
// mapping
var mapping = {
    create: function (options) {
        var innerModel = ko.mapping.fromJS(options.data, {
            'cards': {
                create: function (options) {
                    //debugger;
                    return new cardViewModel(options.data);
                }
            } // etc
        });
// data
var setData = dataservice.getSet();
var observableData = ko.mapping.fromJS(setData, mapping);

在我的 viewModel 中,我想添加如下内容:

self.save = function() {
    var card = new cardViewModel(dataservice.save(this)) // works fine
    innerModel.cards.push(card) // doesn't work because I don't have access to innerModel from the card viewModel
}

现在我只是从viewModels触发事件并从innerModel监听它们,但这有点混乱,想看看是否有任何方法可以从setViewModel访问innerModel.sets()。

4

1 回答 1

0

我会以不同的方式组织它 - 这是否符合您的要求?

var cardViewModel = function (data) {
    // ...
},

cardMapping = {
    create: function(options) {
        return new cardViewModel(options.data);
    }
},

viewModel = function() {
    var self = this;

    var setData = dataservice.getSet();
    self.cards = ko.mapping.fromJS(setData, cardMapping);

    self.save = function() {
        var card = new cardViewModel(dataservice.save(this));
        self.cards.push(card);
    };
};

$(function () {
    var vm = new viewModel();
    ko.applyBindings(vm);
});

我不确定您尝试将保存功能放在哪个视图模型上 - 我将它放在根视图模型上。

于 2013-06-01T22:11:16.940 回答