//wrapper for an observable that protects value until committed
ko.protectedObservable = function(initialValue) {
//private variables
var _temp = initialValue;
var _actual = ko.observable(initialValue);
var result = ko.dependentObservable({
read: _actual,
write: function(newValue) {
_temp = newValue;
}
}).extend({ notify: "always" }); //needed in KO 3.0+ for reset, as computeds no longer notify when value is the same
//commit the temporary value to our observable, if it is different
result.commit = function() {
if (_temp !== _actual()) {
_actual(_temp);
}
};
//notify subscribers to update their value with the original
result.reset = function() {
_actual.valueHasMutated();
_temp = _actual();
};
return result;
};
//construct an Item
var Item = function(name, quantity) {
this.name = ko.protectedObservable(name);
this.quantity = ko.protectedObservable(quantity);
}
var ViewModel = function(items) {
var self = this;
this.items = ko.observableArray(items);
this.selectedItem = ko.observable();
this.addItem = function() {
var newItem = new Item("new item", 0);
self.items.push(newItem);
self.selectedItem(newItem);
};
this.deleteItem = function(itemToDelete) {
self.items.remove(itemToDelete);
self.selectedItem(null);
};
this.editItem = function(item) {
self.selectedItem(item);
};
this.acceptItemEdit = function() {
self.selectedItem().name.commit();
self.selectedItem().quantity.commit();
self.selectedItem(null);
};
this.cancelItemEdit = function() {
self.selectedItem().name.reset();
self.selectedItem().quantity.reset();
self.selectedItem(null);
};
this.templateToUse = function(item) {
return self.selectedItem() === item ? "editTmpl" : "itemTmpl";
};
};
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.