KnockoutJS subscribe to property changes with Mapping Plugin

前端 未结 2 1816
青春惊慌失措
青春惊慌失措 2021-02-01 17:16

Is there anyway I can tell the knockout mapping plugin to subscribe to all property changes call a certain function?

I realize I can manually subscribe to the property c

2条回答
  •  说谎
    说谎 (楼主)
    2021-02-01 18:23

    Here's a generic approach based on Ryan Niemeyer's dirty flag.
    Click here for the JsFiddle.

    Html:

    1. Telephone :
    2. Address :

    Javascript:

    var model = {
        telephone: ko.observable('0294658963'),
        address: ko.observable('167 New Crest Rd')
    
    };
    // knockout extension for creating a changed flag (similar to Ryan's dirty flag except it resets itself after every change)
    ko.changedFlag = function(root) {
        var result = function() {};
        var initialState = ko.observable(ko.toJSON(root));
    
        result.isChanged = ko.dependentObservable(function() {
            var changed = initialState() !== ko.toJSON(root);
            if (changed) result.reset();
            return changed;
        });
    
        result.reset = function() {
            initialState(ko.toJSON(root));
        };
    
        return result;
    };
    // add changed flag property to the model
    model.changedFlag = new ko.changedFlag(model);
    // subscribe to changes
    model.changedFlag.isChanged.subscribe(function(isChanged) {
        if (isChanged)  alert("model changed");
    });
    ko.applyBindings(model);​
    

提交回复
热议问题