I’ve got a knockout View Model that looks like this:
var TagViewModel = function (allPrincipals) {
var self = this;
self.name = ko.observable(tagName);
var principalMapping = {
create: function(options) {
return {
label: options.data.name,
key: options.data.type + '___|' + options.data.name,
icon: options.data.type == "User" ? "img/misc/user20.png" : "img/misc/group20.png"
};
},
key: function(data) {
return data.key;
}
};
self.allPrincipals = ko.mapping.fromJS(allPrincipals, principalMapping);
}
allPrincipals would look something like this:
var allPrincipals = [{name: "Alex" type: "User"}, {name: "John", type: "User"}, {name: "Staff", type: "Group}]
So, when the viewModel is created, we have something like:
var vm = new TagViewModel(allPrincipals);
This works fine.
However, in the view model, I need to be able to push a new item in to the allPrincipals observable array (created by the mapping plugin)
What’s the best way to do this?
So, for example, there’s a function on the view model:
self.addPrincipal = function(prinipal){
//allPrincipals.push(?)
}
You can define a class for creating
Principalobjects:And then use it in mapping options and in
addPrincipalfunction: