1

I come from Angular (which has/had event emitting) and I see that Knockout has 'observables'/pubsub, though I could not fully grasp the concept of this with using separate view models.

Here is an example of what I'm trying to do:

I have an array of objects in VM1 that when an element is updated, I want to emit an event saying that "this object has changed, please update accordingly!" and also passes the object.

I found this on the KO documentation:

For advanced users, if you want to register your own subscriptions to be notified of changes to observables, you can call their subscribe function.

myViewModel.personName.subscribe(function(newValue) {
    alert("The person's new name is " + newValue);
});

However it does not mention who is publishing any changes to "myViewModel". Can anyone clarify this?

In my example, do I bind an observable array to the parent object (possibly ko)?

Edit:

Here is the example:

A user has at least one user that they can manage.

I have one VM that is responsible for displaying a single user's user account settings page. I have another VM that is responsible for displaying all the user's users at a time. If a user clicks on a row (a user's user), a panel comes out to change that row's data. When a row is changed, I want to update the main list of user's users.

HImynameis
  • 55
  • 6
  • Can you come up with a minimal but detailed example of the sort of behavior you're looking for? I don't quite understand why you need to know who made the change, or why you have separate viewmodels. – Roy J Feb 21 '16 at 13:38

1 Answers1

1

I'm going to suggest that you think of these as components rather than VMs. You should have one VM for your application, and it will use these components. It will also own any data items that they need to share. In your example, the user record currently being edited would be owned by the master VM and passed to the components in their initialization. The all-users component could set the value(s) of the current record, and the single-user component will display and allow the edit of the values. The all-users component can subscribe to updates and respond accordingly.

As I see it, the components don't care who is changing the values, they only want to know when values they depend on change. The idea is to have one copy of any distinct, independent data item and share it among the components that need to use it.

Roy J
  • 42,522
  • 10
  • 78
  • 102