Do not know how I can map a field computed using ko.viewmodel anyone knows how it's done? much appreciate any help.
var model = {
firstName: "Le gatêau",
lastName: "Chien",
items: ['J-Rock', 'J-Pop'],
itemselected: 'J-Pop',
all: function(){ return firstName + ', ' + lastName + ', ' + itemselected },
};
EDIT:
I regret not having been more clear, I edit my question, I am using ko.viewmodel plugin to convert an object to a ko model, but not as a field ko.computed the object is defined to ko when maps to be recognized as one computed:
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);
My code complet is here DEMO
EDIT 2:
Thanks for the replies, I put my final code with the functionality I wanted:
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>
The final demo is here FINAL-DEMO
This is tricky, you can do this, but I'm not sure it's the best solution:
http://jsfiddle.net/L6Wm3/3/
Basically, after creating your view model, you will need to manually map that function:
Then when you update you can:
Note that you functions didn't actually work anyway and need to be changed:
Alternatively, you can just add a
ko.computed
to your view model, so long as theall
function is always the same:And then bind to that instead of
all
. This has the added advantage that it'll just work when you update the binding.http://jsfiddle.net/L6Wm3/5/
If I am getting your problem right, you want a
ko.computed
property on your model. Theko.viewModel
pluggin providesoptions
to control your viewModel. Use theextend
option to create the computed propertyall
instead of directly adding to object. I have created a fiddle for same: http://jsfiddle.net/sublimejs/L6Wm3/8/.