Reputation: 4867
I still have some problems structuring my knockoutjs models.
The data which I got from server looks like this:
var data = {
Creation: "2012-01-01T00:00:00Z",
Id: 3,
LastActivity: null,
Name: "Foo",
Permissions: {
IsAdmin: false,
IsInternal: false,
// ... some more boolean
},
};
Now I create a model like this:
var getDetails = function (user, edit) {
UserModel = function() {
var self = this;
user = user || {
Id: 0,
Username: '',
Creation: new Date(),
LastActivity: new Date(),
Name: '',
Permissions: {
IsAdmin: false,
IsInternal: false,
// ... some more boolean
},
Stores: []
};
this.Id = ko.observable(user.Id);
this.Username = ko.observable(user.Username);
this.Creation = ko.observable(user.Creation);
this.LastActivity = ko.observable(user.LastActivity);
this.Name = ko.observable(user.Name);
// how handle the permissions ???
};
The Permissions like IsAdmin, IsInternal, etc
I have to use in checkedboxes. All are booleans.
Now my questions, how is the best way to handle the permissions object. Create an own model? Or can I use something like this:
this.Permissions.IsAdmin = ko.observable(user.Permissions.IsAdmin);
Upvotes: 0
Views: 169
Reputation: 11225
I would approach this by creating another view model for the permissions type since it is a complex type and needs to store multiple values. Hooray Object-Oriented Programming!
For example:
var PermissionsModel = function(permissions){
var self = this;
self.IsAdmin = ko.observable(permissions.IsAdmin || false);
self.IsInternal = ko.observable(permissions.IsInternal || false);
}
Then in your UserModel
add a Permissions
property like so:
var UserModel = function(user, edit) {
var self = this;
self.Id = ko.observable(user.Id || 0);
self.Username = ko.observable(user.Username || "");
self.Creation = ko.observable(user.Creation || new Date());
self.LastActivity = ko.observable(user.LastActivity || new Date());
self.Name = ko.observable(user.Name || "");
self.Permissions = new PermissionsModel(user.permissions || {});
}
Now, you can pass your data.permissions
object directly off to your new view model and let it worry about instantiating those properties.
observable
function. The plus side of this is that you no longer need to create an anonymous object within your class. Also, when you go to add/edit your model, you don't have to keep track of that object anymore. You can just change/add the properties directly.
Upvotes: 4