Question

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:

  1. The best way to list out the users by accessing the users viewModel from their respective id's in the convos viewModel.

  2. 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.

Was it helpful?

Solution

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.

OTHER TIPS

Normally you'd do something like this (presuming Convos is a top-level observableArray that contains Convo entries):

<ul data-bind="foreach: Convos">
  <li>Conversation <span data-bind="name"></span>
     <ul data-bind="foreach: users">
        <li><span data-bind="text: name"></span> has status
            <span data-bind="text: status"></span>
        </li>
     </ul>
  </li>
</ul>

Since everything involved is observable, any change to, for example, a user's status will automatically update the display (as would adding/removing a user or a convo).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top