不知道如何映射使用 ko.viewmodel 计算的字段有人知道它是如何完成的吗?非常感谢任何帮助。
var model = {
firstName: "Le gatêau",
lastName: "Chien",
items: ['J-Rock', 'J-Pop'],
itemselected: 'J-Pop',
all: function(){ return firstName + ', ' + lastName + ', ' + itemselected },
};
编辑:
我很遗憾没有更清楚,我编辑了我的问题,我正在使用 ko.viewmodel 插件将对象转换为 ko 模型,但不是作为字段 ko.computed 对象被定义为 ko 当地图被识别为一个计算:
var updatedModel = {
firstName: "El pastel",
lastName: "Perro",
items: ['Pop', 'Rock'],
itemselected: 'Rock',
all: function(){ return firstName + ', ' + lastName + ', ' + itemselected },
};
var viewModel = ko.viewmodel.fromModel(model);
ko.applyBindings(viewModel);
我的完整代码在这里DEMO
编辑2:
感谢您的回复,我将最终代码与我想要的功能放在一起:
JS:
var options = {
extend: {
"{root}": function (m) {
m.all = ko.computed(function () {
var item = ko.utils.arrayFirst(m.music(), function (g) {
return g.id() == m.selected();
});
if (item == null) return '';
return m.like() + ' ' + item.name();
});
}
}
};
var m1 = '{"like":"Pastel","music":[{"id":1,"name":"J-Pop"},{"id":2,"name":"J-Rock"},{"id":3,"name":"Rock"}],"selected":"3"}';
var m2 = '{"like":"Gatêau","music":[{"id":1,"name":"J-Pop"},{"id":2,"name":"J-Rock"},{"id":3,"name":"Rock"}],"selected":"2"}';
var viewmodel = ko.viewmodel.fromModel(JSON.parse(m1), options);
ko.applyBindings(viewmodel);
setTimeout(function () {
console.clear();
ko.viewmodel.updateFromModel(viewmodel, JSON.parse(m2));
}, 2300)
HTML:
Comida:
<input data-bind="value: like" />
<br/>Musica:
<select data-bind="options: music, optionsText: 'name', optionsValue: 'id', value: selected"></select>
<br/>
<h1 data-bind="text: all"></h1>
最后的演示在这里FINAL-DEMO