0

刚开始淘汰,需要实现页面更改警告。以下是代码片段。如果页面上有任何更改,我只需要弹出一个警告作为警告。

function parseViewModel() {

    var viewModel = JSON.parse(getState());

    viewModel.checking = ko.observable(false);
    viewModel.Slider = new ko.observable(100 - viewModel.Slider);
    viewModel.CausalsList = buildHierarchy(viewModel.Causals);
    viewModel.Causals["-1"] = "Total Marketing Budget";
    viewModel.GeographiesList = ko.observableArray(gl);
    viewModel.Geographies["0"] = "All Geographies";
    viewModel.ProductsList = ko.observableArray(pl);
    viewModel.Products["0"] = "All Products";
    .
    .
    .

    return viewModel;
}

function bindModel() {

    model = parseViewModel();

    ko.dirtyFlag = function (root, isInitiallyDirty) {
        var result = function () { },
        _initialState = ko.observable(ko.toJSON(root)),
        _isInitiallyDirty = ko.observable(isInitiallyDirty);

        result.isDirty = ko.computed(function () {
            return _isInitiallyDirty() || _initialState() !== ko.toJSON(root);
        });

        result.reset = function () {
            _initialState(ko.toJSON(root));
            _isInitiallyDirty(false);
        };

        return result;
    };


    model.dirtyFlag = new ko.dirtyFlag(model);
    model.isDirty.subscribe(function () {
        alert("Page change warning!");
    });

    ko.applyBindings(model, $('#const').get(0));
    ko.applyBindings(model, $('#buttonDiv').get(0));
}

参考了 Ryan Niemeyer 的博客。不幸的是,它不再起作用了。请问有什么见解吗?

4

2 回答 2

3

在您的情况下,您可能希望订阅model.dirtyFlag.isDirty而不是model.isDirty.

于 2013-07-27T00:37:16.737 回答
0

一种方法是使用 customBinding。我对 KO 也不是很熟悉,但这可能是你感兴趣的东西。

基本上你会做的是: -

ko.bindingHandlers.myFunction = {
    update : function(){
                //do something
             }
}

http://knockoutjs.com/documentation/custom-bindings.html

并使用以下方法在您的元素上调用它:-

<h1 data-bind="myFunction:{}"></h1>

此外,还有一个 jsfiddle 来展示它是如何工作的。(如果您更改 First Name 的值并将注意力放在它之外,那么 customBinding 就会被触发。)

http://jsfiddle.net/3vuTk

不确定这是否是最佳做法。

于 2013-07-27T00:34:53.817 回答