Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple, clean way to sync observables from different view models

Say I have two view models that each have an observable property that represents different, but similar data.

function site1Model(username) {
    this.username = ko.observable(username);
    ....
}

function site2Model(username) = {
    this.username = ko.observable(username);
    ....
}

These view models are independent and not necessarily linked to each other, but in some cases, a third view model creates a link between them.

function site3Model(username) = {
    this.site1 = new site1Model(username);
    this.site2 = new site2Model(username);
    // we now need to ensure that the usernames are kept the same between site1/2
    ...
}

Here are some options that I've come up with.

  1. Use a computed observable that reads one and writes to both:

    site3Model.username = ko.computed({
        read: function() {
            return this.site1.username();    // assume they are always the same
        },
        write: function(value) {
            this.site1.username(value);
            this.site2.username(value);
        },
        owner: site3Model
    }
    

    This will keep the values in sync as long as changes always come through the computed. But if an underlying observable is changed directly, it won't do so.

  2. Use the subscribe method to update each from the other:

    site3Model.site1.username.subscribe(function(value) {
        this.site2.username(value);
    }, site3Model);
    site3Model.site2.username.subscribe(function(value) {
        this.site1.username(value);
    }, site3Model);
    

    This works as long as the observables suppress notifications when the values are the same; otherwise you'd end up with an infinite loop. You could also do the check earlier: if (this.site1.username() !== value) this.site1.username(value); This also has a problem that the observables have to be simple (it won't work right if site1 and site2 themselves are observables).

  3. Use computed to do the subscribe and updates:

    site3Model.username1Updater = ko.computed(function() {
        this.site1.username(this.site2.username());
    }, site3Model);
    site3Model.username2Updater = ko.computed(function() {
        this.site2.username(this.site1.username());
    }, site3Model);
    

    This format allows us to have other dependencies. For example, we could make site1 and site2 observables and then use this.site1().username(this.site2().username()); This method also requires a check for equality to avoid an infinite loop. If we can't depend on the observable to do it, we could check within the computed, but would add another dependency on the observable we're updating (until something like observable.peek is available). This method also has the downside of running the update code once initially to set up the dependencies (since that's how computed works).

Since I feel that all of these methods have a downside, is there another way to do this that would be simple (less than 10 lines of code), efficient (not run unnecessary code or updates), and flexible (handle multiple levels of observables)?

like image 580
Michael Best Avatar asked May 30 '12 01:05

Michael Best


3 Answers

It is not exactly 10 lines of code (although you could strip it down to your liking), but I use pub/sub messages between view models for this situation.

Here is a small library that I wrote for it: https://github.com/rniemeyer/knockout-postbox

The basic idea is just to create a ko.subscribable and use topic-based subscriptions. The library extends subscribables to add subscribeTo, publishOn and syncWith (both publish and subscribe on a topic). These methods will set up the proper subscriptions for an observable to automatically participate in this messaging and stay synchronized with the topic.

Now your view models do not need to have direct references to each other and can communicate through the pubsub system. You can refactor your view models without breaking anything.

Like I said you could strip it down to less than 10 lines of code. The library just adds some extras like being able to unsubscribe, being able to have control over when publishing actually happens (equalityComparer), and you can specify a transform to run on incoming values.

Feel free to post any feedback.

Here is a basic sample: http://jsfiddle.net/rniemeyer/mg3hj/

like image 160
RP Niemeyer Avatar answered Nov 15 '22 08:11

RP Niemeyer


Ryan and John, Thank you both for your answers. Unfortunately, I really don't want to introduce a global naming system that the pub/sub systems require.

Ryan, I agree that the subscribe method is probably the best. I've put together a set of functions to handle the subscription. I'm not using an extension because I also want to handle the case where the observables themselves might be dynamic. These functions accept either observables or functions that return observables. If the source observable is dynamic, I wrap the accessor function call in a computed observable to have a fixed observable to subscribe to.

function subscribeObservables(source, target, dontSetInitially) {
    var sourceObservable = ko.isObservable(source) 
            ? source 
            : ko.computed(function(){ return source()(); }),
        isTargetObservable = ko.isObservable(target),
        callback = function(value) {
            var targetObservable = isTargetObservable ? target : target(); 
            if (targetObservable() !== value)
                targetObservable(value);
        };
    if (!dontSetInitially)
        callback(sourceObservable());
    return sourceObservable.subscribe(callback);
}

function syncObservables(primary, secondary) {
    subscribeObservables(primary, secondary);
    subscribeObservables(secondary, primary, true);
}

This is about 20 lines, so maybe my target of less than 10 lines was a bit unreasonable. :-)

I modified Ryan's postbox example to demonstrate the above functions: http://jsfiddle.net/mbest/vcLFt/

like image 20
Michael Best Avatar answered Nov 15 '22 08:11

Michael Best


Another option is to create an isolated datacontext that maintains the models of observables. the viewmodels all look to the datacontext for their data and refer to the same objects, so when one updates, they all do. The VM's dependency is on the datacontext, but not on other VMs. I've been doing this lately and it has worked well. Although, it is much more complex than using pub/sub.

If you want simple pub/sub, you can use Ryan Niemyer's library that he mentioned or use amplify.js which has pub/sub messaging (basically a messenger or event aggregator) built in. Both are lightweight and decoupled.

like image 44
John Papa Avatar answered Nov 15 '22 08:11

John Papa