Whats the best way of linking/synchronising view models in Knockout?

后端 未结 4 1237
时光取名叫无心
时光取名叫无心 2020-12-08 03:07

If you have several view models on one page, how do you ensure that you can keep them synced? For example, if one item is added or a button clicked on one view model and you

4条回答
  •  隐瞒了意图╮
    2020-12-08 03:52

    Knockout 2.0 does include functionality that lets you do basic pub/sub. Here is a sample where two view models communicate through a mediator.

    var postbox = new ko.subscribable();
    
    var ViewModelOne = function() {
        this.items = ko.observableArray(["one", "two", "three"]);
        this.selectedItem = ko.observable();
        this.selectedItem.subscribe(function(newValue) {
            postbox.notifySubscribers(newValue, "selected");
        });
    };
    
    var ViewModelTwo = function() {
        this.content = ko.observable();
        postbox.subscribe(function(newValue) {
            this.content(newValue + " content");
        }, this, "selected");
    };
    
    ko.applyBindings(new ViewModelOne(), document.getElementById("choices"));
    ko.applyBindings(new ViewModelTwo(), document.getElementById("content"));
    

    The first view model notifies through the postbox on a specific topic and the second view model subscribes to that topic. They have no direct dependency on each other.

    Certainly the postbox would not need to be global and could be passed into the view model constructor functions or just created inside a self-executing function.

    Sample: http://jsfiddle.net/rniemeyer/z7KgM/

    Also, the postbox could just be a ko.observable (which includes the ko.subscribable functions).

提交回复
热议问题