Reputation: 4259
I'm just getting my feet of the ground with knockout and before I munge together some abomination of code I was wondering If anyone could help with the following:
I have a group array
[{
"id": 1,
"name" : "tekken characters",
"members": [1, 3]
}, //etc]
and a members array
[{ "id": 1, "name": "nina williams" }, {"id": 2, "name": "super mario"}, {"id": 3, "yoshi mitsu"}]
Both are returned via seperate API calls. There is a parent child (one to many) relationship. What is the best pattern to apply to this sort of data using Knockout.js?
Though I do use each array individually, for example I have a list of all my groups and a list of all my members, I also want a list of groupMembers. Notice not all members belong to each group. Is this a computed value where I map ids to each other or, what's the best approach? The calls are all ajax based so timing is important.
If anyone has done this, or knows of good resources to handle these sorts of relationship/data structures it'd be useful to share them.
Upvotes: 0
Views: 786
Reputation: 943
If I understand you correctly then the KO view model might look something like this:
function viewModel() {
var self = this;
self.groups = ko.observableArray([]);
self.members = ko.observableArray([]);
self.addToGroups = function(data) {
// Add a new group/groups to view model (e.g. with AJAX)
};
self.addToMembers = function(data) {
// Add a new member/members to view model
};
self.membersInGroups = ko.computed(function() {
// Do some logic like getting members in groups
}, this);
}
Then I would use view models for both groups and members:
function groupViewModel(data) {
var self = this;
self.id = ko.observable(data.id);
self.name = ko.observable(data.name);
self.members = ko.observableArray(data.members);
}
function memberViewModel(data) {
var self = this;
self.id = ko.observable(data.id);
self.name = ko.observable(data.name);
}
Check out fiddle: http://jsfiddle.net/DcaP2/
Upvotes: 1