I'm learning Knockout and I'm stuck on what seems to be a fairly trivial issue. Below is some modified code but most of it is from the Pluralsight course. I'm using MVC4 and all my data is coming from a controller in JSON.
Public Function GetData() As ActionResult
Return Json(dataContext.GetData, JsonRequestBehavior.AllowGet)
End Function
Here is my view
<ul data-bind="foreach: items">
<li >
<input type="text" id="name" data-bind="value: name" />
</li>
</ul>
And my view model :
$(document).ready(function () {
ko.dirtyFlag = function (root) {
var result = function () { },
_initialState = ko.observable(ko.toJSON(root))
result.isDirty = ko.dependentObservable(function () {
return _initialState() !== ko.toJSON(root);
});
result.reset = function () {
_initialState(ko.toJSON(root));
};
return result;
};
function Customer(data) {
this.name = ko.observable(data.name);
this.id = ko.observable(data.id);
this.dirtyFlag = new ko.dirtyFlag(this);
}
var ViewModel = function (items) {
var self = this;
this.items = ko.observableArray([]);
this.save = function () {
alert("update");
};
this.addNew = function () {
alert("add");
};
this.deleteItem = function () {
alert("delete");
};
this.dirtyItems = ko.computed(function () {
return ko.utils.arrayFilter(this.items(), function (item) {
return item.dirtyFlag.isDirty();
});
}, this);
this.isDirty = ko.computed(function () {
return this.dirtyItems().length > 0;
}, this);
$.getJSON("/home/GetCustomers", function (allData) {
var mappedLoadouts = $.map(allData, function (item) { return new Customer(item) });
self.items(mappedLoadouts);
});
};
ko.applyBindings(new ViewModel());
Please note this code has been changed to simplify the example.
My first question is, why doesn't this work? I keep getting a 'DirtyItems' can be found, can anyone tell me why? I can't see a scope issue because I'm referring to customers in the same context.
Also, all of the help that I found so far uses a different approach to the Javascript all together. Just like this similar question Best way to get only modified rows from observableArray (when there is bulk edit option). When I attempted to rebuild my viewmodel to follow this example, I received an error on the foreach : Customers (same error as the DirtyItems).
This was a promising question, but the answer again used the other Javascript approach Knockout dirty flag event
Any advice is appreciated!