Simple, clean way to sync observables from different view models

百般思念 提交于 2019-11-30 09:55:37

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/

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/

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.

In case anyone needed. Another option is to create a reference object/observable. This also handle object that contains multiple observable.

(function(){
    var subscriptions = [];

    ko.helper = {
        syncObject: function (topic, obj) {
            if(subscriptions[topic]){
                return subscriptions[topic];
            } else {
                return subscriptions[topic] = obj;
            }
        }
    };
})();

In your view models.

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

function site2Model(username) = {
    this.username = syncObject('username', ko.observable());
    this.username(username);
    ....
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!