我想使用带有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;
}());
但我可以宣布订阅者和&仅在映射后计算可观察量。这是正确的方法吗?
答案 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);
};
更新时,您只需再次致电ko.mapping.fromJS(data, mapping, this)