knockout.js - KnockoutJs mapping to view model complex property -
i new knockout , trying thought simple scenario, not working. neither of 2 input's changes when selection changes, , select list not initialise selectedformat.
html:
<input type="text" data-bind="value: selectedformat.id" /> <input type="text" data-bind="enable: selectedformat.fields()[0].enabled" /> <select data-bind="options: formats, optionstext: 'name', value: selectedformat" /> js:
var data = { formats: [ { id: 1, name: 'format 1', fields: [ { id: 1, enabled: true }, ]}, { id: 2, name: 'format 2', fields: [ { id: 1, enabled: false }, ]} ], selectedformat: { id: 2, name: 'format 2', fields: [ { id: 1, enabled: false }, ]} } var vm = ko.mapping.fromjs(data); ko.applybindings(vm);
you there in fiddle, parts there need connect.
te mapping plugin don't create automatically observables properties holding complexs object. default selectedformat won't observable after mapping. because want write value: selectedformat has observable therefore need custom mapping configuration makes selectedformat observable:
var mapping = { 'selectedformat': { create: function(options) { return ko.observable(ko.mapping.fromjs(options.data)); } } } if definied create function responsible mapping of value need call ko.mapping.fromjs inside create function options.data map values inside selectedformat observable.
then need tell ko.mapping use mapping config with:
var vm = ko.mapping.fromjs(data, mapping); and need change bindings because selectedformat observable need value selectedformat():
<input type="text" data-bind="value: selectedformat().id" /> <input type="text" data-bind="enable: selectedformat().fields()[0].enabled" /> demo jsfiddle.
if want initial selection work, mapping needs lookup selected item id instead of creating new object:
var mapping = { 'selectedformat': { create: function(options) { var selected = ko.utils.arrayfirst(options.parent.formats(), function(item){ return item.id() == options.data.id; }); return ko.observable(selected); } } } demo jsfiddle.
Comments
Post a Comment