[英]knockout dirty flag code not working
Just started with knockout and need to implement page change warning. 刚从淘汰赛开始,需要实施页面更改警告。 Following is the code snippet. 以下是代码段。 I just need an alert pop up as warning if any change is made on the page. 如果页面上有任何更改,我只需要弹出一个警告作为警告即可。
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));
}
Referred Ryan Niemeyer's blog. 推荐Ryan Niemeyer的博客。 Unfortunately, it's not working anymore. 不幸的是,它不再工作了。 Any insights please? 有什么见解吗?
您可能要在您的情况下订阅model.dirtyFlag.isDirty
而不是model.isDirty
。
One way to do is by using customBinding. 一种方法是使用customBinding。 I'm not that familiar with KO either but this might be something you're interested on. 我对KO也不太熟悉,但这可能是您感兴趣的东西。
Basically you would do is :- 基本上你会做的是:
ko.bindingHandlers.myFunction = {
update : function(){
//do something
}
}
http://knockoutjs.com/documentation/custom-bindings.html http://knockoutjs.com/documentation/custom-bindings.html
And call it on your element using :- 并使用:-在元素上调用它
<h1 data-bind="myFunction:{}"></h1>
Also, a jsfiddle to show how it works. 另外,一个jsfiddle展示了它是如何工作的。 (If you change the value of the First Name and focus out of it then the customBinding gets triggered. ) (如果您更改First Name的值并将其焦点移出,则将触发customBinding。)
http://jsfiddle.net/3vuTk http://jsfiddle.net/3vuTk
Not sure if it's the best practice though. 不确定这是否是最佳做法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.