Reputation: 5304
I am trying to figure out how to add an additional attribute to an observable array using the ko mapping plugin. so for example if I have data like this
var items = [{
foo1: 'bar1',
foo2: 'bar2',
foo3: 'bar3'
}, {
foo1: 'bar4',
foo2: 'bar5',
foo3: 'bar6'
}];
and my I can bind to my knockout observable like this
function viewModel() {
var self = this;
this.items = ko.observableArray('');
}
var vm = new viewModel();
(function($) {
ko.applyBindings(vm); //bind the knockout model
ko.mapping.fromJS(items, {}, vm.items); // map the data to the
})(jQuery);
but what if in the items array I would like each item to have an additional attribute. such as editMode: false. what do I have to do to the mapping to make that happen. I believe it has something to do with the create callback but I can't quite figure it out.
here is my fiddle https://jsfiddle.net/0o89pmju/5/. I can't quite figure out how to use the create function on the mapping to add the additional attribute of editMode with a value of false to each item in the array of items.
Upvotes: 0
Views: 892
Reputation: 994
Perhaps there is a better solution.
You could call the mapping pluging this way:
ko.mapping.fromJS(items, mapping,vm.items);
mapping
is an object with a create
function:
var mapping = {
create: function(options) {
return new dummyModel(options.data);
}
}
And dummyModel
is a temporary object than holds the new properties you want to add, and the ones that come from the plugin:
var dummyModel = function(data) {
ko.mapping.fromJS(data, {}, this);
// New Properties
this.editMode = ko.observable(false)
}
Here is a fiddle to play with.
Hope this helps.
PD: Source of info in this link Pluggin Mapping (Customizing object construction using “create”)
Upvotes: 1