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

后端 未结 4 1236
时光取名叫无心
时光取名叫无心 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:51

    The way I found to synchronising models is using the postbox library of RP Niemeyer

    However I found something interesting regarding the observableArray. And that's why I created a new answer. Just to complete the answer from Niemeyer.

    When using postbox and an observableArray the "subscribeTo" and "publishOn" events are fired when you add or remove an element from the observableArray. It doesn't fire anything when you update an element within the array. I think this doesn't have anything to do with the postbox library but a knockout limitation.

    If you are attempting to get the event when updating an element of an observable array it's better to use "publish" and "subscribe" methods from the postbox library.

    Please see the following FIDDLE

    Code reference:

    function FundEntity (fund)
    {
        var self = this;
        self.id = fund.id;
        self.fundName = fund.fundName;
        self.description = fund.description;
        self.isFavorite = ko.observable(fund.isFavorite);
    }
    
    
    function GridViewModel(model) {
        var self = this;
        self.fundList = ko.observableArray();
        model.funds.forEach(function(fund) {
            self.fundList.push(new FundEntity(fund));
        }); 
        self.favorite = function (id, index) {
            var newValue = {
                id: id,
                index: index,
                isFavorite: self.fundList()[index].isFavorite()
            };
            ko.postbox.publish("itemChanged", newValue);
            return true;
        };
        self.isEditable = ko.observable().subscribeTo("myEditableTopic");
    }
    
    function FundDetailViewModel(model) {
        var self = this;
        self.fundList = ko.observableArray();
        model.funds.forEach(function(fund) {
            self.fundList.push(new FundEntity(fund));
        });    
        ko.postbox.subscribe("itemChanged", function (newValue) {        
            self.fundList()[newValue.index].isFavorite(newValue.isFavorite);        
        });
        self.editable = ko.observable(false).publishOn("myEditableTopic");
    }
    

提交回复
热议问题