How to create dirty flag functionality
javascript, knockout.js
Solution
Your code has several problems:
You are defining the `dirtyFlag` on your `Task` function. But you are checking it on the view bound to the viewModel instance.
You have to define the dirty flag after you loaded the data or you have to call `dirtyFlag().reset()`.
`isDirty` is a computed. You have to call it with parenthesis.
The view model looks like:
function TaskListViewModel() {
// Data
function Task(data) {
this.title = ko.observable(data.title);
this.isDone = ko.observable(data.isDone);
}
var self = this;
self.tasks = ko.observableArray([]);
self.newTaskText = ko.observable();
self.incompleteTasks = ko.computed(function() {
return ko.utils.arrayFilter(self.tasks(), function(task) { return !task.isDone() && !task._destroy });
});
this.dirtyFlag = new ko.DirtyFlag(this.isDone);
// Operations
self.addTask = function() {
self.tasks.push(new Task({ title: this.newTaskText() }));
self.newTaskText("");
};
self.removeTask = function(task) { self.tasks.destroy(task) };
self.save = function() {
$.ajax("/echo/json/", {
data: {
json: ko.toJSON({
tasks: this.tasks
})
},
type: "POST",
dataType: 'json',
success: function(result) {
self.dirtyFlag().reset();
alert(ko.toJSON(result))
}
});
};
//Load initial state from server, convert it to Task instances, then populate self.tasks
$.ajax("/echo/json/", {
data: {
json: ko.toJSON(fakeData)
},
type: "POST",
dataType: 'json',
success: function(data) {
var mappedTasks = $.map(data, function(item) {
return new Task(item);
});
self.tasks(mappedTasks);
self.dirtyFlag().reset();
}
});
}
The binding for the cancel button:
<button data-bind="enable: dirtyFlag().isDirty()">Cancel</button>
And the working fiddle (a fork of yours) can be found at: http://jsfiddle.net/delixfe/ENZsG/6/
Problem
I want to create dirty flag functionality using knockout. I want to enable the save button only if something has changed. My view and my view model is exactly same as example found on knockout js tutorial Loading and Saving data. Link to tutorial I am following fiddle example posted by Ryan here I am not able to understand where to declare below code which he has declared in view model. ``` this.dirtyFlag = new ko.dirtyFlag(this); ``` If i take example from knockout tutorial the link which i posted above and i tried like below ``` function Task(data) { this.title = ko.observable(data.title); this.isDone = ko.observable(data.isDone); this.dirtyFlag = new ko.dirtyFlag(this); ``` } Binded my view like below ``` <button data-bind="click: saveOperation , enable: isDirty" >Save</button> ``` It gives me error as unable to parse binding isDirty is not defined. I am not sure how to go on implementing this.