I am building a simple chat application with 2 main components: conversations (convos) and users.
Users have the following properties: id
, name
, status
Convos have the following properties: id
, name
, users
In convos, the users
is an observableArray
of the id
's of the users involved in that convo.
My goal is to list out the users (by name) in the convos view, but I'm looking for some guidance on two items:
The best way to list out the users by accessing the users
viewModel from their respective id
's in the convos viewModel.
How to keep an association so when (for example) a user changes their status from active
to away
the status on any convos where their id
exists updates the viewModel.
At this point I have the viewModels in place, but not much else, I'm hoping someone can provide some guidance or an example of how this can be (reliably) accomplished.
The answer is probably to not list users by their ID in the convos view model. Instead, list the actual users by reference. This will make both of your problems go away as Knockout will handle the bindings (two-way, if needed) for you.
Here's an example of what I mean:
var User = function(id,name,status) {
this.id = ko.observable(id);
this.name = ko.observable(name);
this.status = ko.observable(status);
};
var Convo = function(id,name,users) {
this.id = ko.observable(id);
this.name = ko.observable(name);
this.users = ko.observableArray(users);
};
var john = new User(1,'john','active');
var mary = new User(2,'mary','inactive');
var marcus = new User(3,'marcus','active');
var convo1 = new Convo(1, 'dinner', [john,mary]);
var convo2 = new Convo(2, 'birth day party tomorrow', [john,mary,marcus]);
That way if you refer to a user's status somewhere within a conversation, it will be kept in synch with your view model automatically.
See this fiddle for a demo of what I mean.