这应该是一个简单的问题,但我无法弄清楚如何做或找到正确的答案。我正在尝试实现changeTracker here,但我有一个viewModel函数,而不仅仅是一个变量。我正在使用
var viewModel = function () {
// code
}
并使用
应用绑定var vm = new viewModel();
ko.applyBindings(vm);
如何将changeTracker合并到我的应用程序中?我试过了
var vm = new changeTracker(viewModel());
和
var vm = new changeTracker(new viewModel());
但不起作用。 changeTracker小提琴html是:
<p>Text property: <input data-bind="value: someTextProperty" /></p>
<p>Bool property: <input type="checkbox" data-bind="checked: boolProperty" /></p>
<p>Array items count: <span data-bind="text: arrayItems().length"></span> <button data-bind="click:addItem">Add</button></p>
<hr/>
<p>Something has changed? <b data-bind="text: tracker().somethingHasChanged() ? 'YES' : 'NO'"></b></p>
<button data-bind="click: tracker().markCurrentStateAsClean, enable: tracker().somethingHasChanged">
Mark current state as clean
</button>
和javascript是:
function changeTracker(objectToTrack, hashFunction) {
hashFunction = hashFunction || ko.toJSON;
var lastCleanState = ko.observable(hashFunction(objectToTrack));
var result = {
somethingHasChanged : ko.dependentObservable(function() {
return hashFunction(objectToTrack) != lastCleanState()
}),
markCurrentStateAsClean : function() {
lastCleanState(hashFunction(objectToTrack));
}
};
return function() { return result }
}
var viewModel = {
someTextProperty: ko.observable("Hello"),
boolProperty: ko.observable(false),
arrayItems: ko.observableArray([]),
addItem : function() { this.arrayItems.push("Another") }
};
viewModel.tracker = new changeTracker(viewModel);
ko.applyBindings(viewModel);
答案 0 :(得分:1)
我改变了jsFiddle是使用构造函数,它没有问题。您将changeTracker附加到viewModel,您不能使用作为绑定viewModel返回的changeTracker实例。
var ViewModel = function() {
this.someTextProperty = ko.observable("Hello");
this.boolProperty = ko.observable(false);
this.arrayItems = ko.observableArray([]);
this.addItem = function() { this.arrayItems.push("Another"); };
};
var viewModel = new ViewModel();
viewModel.tracker = new changeTracker(viewModel);
ko.applyBindings(viewModel);