1

我想使用带有淘汰视图模型的映射插件:

var TasksListViewModel = (function () {
    var self = this;
    var GET_PATH = "/Tasks/Index";

    self.loadData = function() {
        $.getJSON(GET_PATH, function (data) {
            ko.mapping.fromJS(data, {}, self);
            setSubscribers();
            setComputed();
            ko.applyBindings(self);            
        });
    };

    self.updateData = function() {
        $.getJSON(GET_PATH,
            {
                page: self.Page()                
            }, function (data) {
            ko.mapping.fromJS(data, TasksListViewModel);
        });
    };

    self.setSubscribers = function() {
        self.Page.subscribe(function (newPage) {            
             self.updateData();
        });       
    };

    self.setComputed = function () {
        self.TotalPages = ko.computed(function () {
            return Math.ceil(self.Total() / self.PageSize());
        });        
    }

    return self;
}());

但是我只能在映射后声明订阅者和计算的 observables。这是正确的方法吗?

4

1 回答 1

0

我个人喜欢这种方法

ViewModel = function(data) {
    var mapping = {
        myArray: {
            create: function(options) {
                return new ChildViewModel(options.data);
            }
        }
    };

    ko.mapping.fromJS(data, mapping, this);

    this.computed = ko.computed(this.getComputed, this);
};

ViewModel.prototype = {
    getComputed: function() {
        return this.myData() + "computed";
    }
};

ChildViewModel = function(data) {
    ko.mapping.fromJS(data, {}, this);
};

http://jsfiddle.net/QEKyP/1

更新时,您只需ko.mapping.fromJS(data, mapping, this)再次调用

于 2013-09-26T22:01:13.450 回答