var addArrayMethods = function(val, actual) {
//add observableArray specific methods
ko.utils.arrayForEach(["remove", "removeAll", "destroy", "destroyAll", "replace"], function (methodName) {
val[methodName] = ko.observableArray.fn[methodName].bind(actual);
});
//call observableArray notifications and apply native array methods (since they are being replaced)
ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) {
val[methodName] = function () {
actual.valueWillMutate();
var methodCallResult = [][methodName].apply(val, arguments);
actual.valueHasMutated();
return methodCallResult;
};
});
};
var observableModel = function(target, props) {
//loop through the properties that were provided
ko.utils.arrayForEach(props || [], function(prop) {
var actual, isArray, initial = target[prop];
if (Array.isArray(initial)) {
actual = ko.observableArray(initial);
isArray = true;
addArrayMethods(initial, actual);
} else {
actual = typeof initial != "function" ? ko.observable(initial) : ko.computed(initial, target);
}
//observables/computeds are already set up to act getters/setters
//this actually redefines the existing property on the object that was provided
Object.defineProperty(target, prop, {
get: actual,
set: function(newValue) {
var val, fn;
actual(newValue);
val = actual.peek();
//if this was originally an observableArray, then always check to see if we need to add/replace the array methods (if newValue was an entirely new array)
if (isArray && !val.destroyAll) {
//don't allow null, force to an empty array
if...
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.