使用映射实现ViewModel的最佳方法(使用knockout)

时间:2013-09-26 17:52:49

标签: knockout.js

我想使用带有knockout viewmodel的映射插件:

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;
}());

但我可以宣布订阅者和&仅在映射后计算可观察量。这是正确的方法吗?

1 个答案:

答案 0 :(得分: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)