KnockoutJS subscribe to property changes with Mapping Plugin

和自甴很熟 提交于 2019-12-02 20:15:57

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

Html:

<ol>
<li>
    Telephone : <input data-bind="value: telephone"/>
</li>
<li>
    Address : <input data-bind="value: address"/>
</li>
</ol>​

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);​
Ziad

This handy little plugin is pretty close to what you did but it comes with several options and can work over a much broader set of requirements without requiring the Mapping plugin:

https://github.com/ZiadJ/knockoutjs-reactor

Basically it allows you to write this kind of code:

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