Created
August 22, 2014 10:36
-
-
Save capaj/bcb774600ca4486695ab to your computer and use it in GitHub Desktop.
just puny exercies trying to make deepObserve happen
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head lang="en"> | |
<meta charset="UTF-8"> | |
<title></title> | |
</head> | |
<body> | |
<script type="text/javascript"> | |
// Let's say we have a model with data | |
var propObj = {}; | |
var model = []; | |
console.log("init"); | |
// Which we then observe | |
deepObserve(model, function(changes){ | |
// This asynchronous callback runs | |
changes.forEach(function(change) { | |
// Letting us know what changed | |
console.log(change.type, change.name, change.oldValue); | |
}); | |
}); | |
setTimeout(function(){ | |
model.prop = propObj; | |
}, 10); | |
setTimeout(function(){ | |
propObj.a = 10; | |
propObj.b = 'fefe'; | |
model.prop = propObj; | |
}, 130); | |
setTimeout(function(){ | |
model.prop = undefined; | |
}, 150); | |
//////////////////////////////////// | |
function isObject(value){ | |
// http://jsperf.com/isobject4 | |
return value !== null && typeof value === 'object' && !Array.isArray(value); | |
} | |
function deepObserve(obj, CB, notifier, previousPath) { | |
var notf = Object.getNotifier(obj); | |
var keys = Object.keys(obj); | |
if (!previousPath) { | |
previousPath = []; | |
} | |
var recourse = function(rObj, pathToAdd) { | |
previousPath.push(pathToAdd); | |
deepObserve(rObj, CB, notf, pathToAdd); | |
}; | |
var key; | |
while(key = keys.pop()) { | |
if (typeof obj[key] === 'object') { | |
console.log("Observing property " + key ); | |
recourse(obj[key], key); | |
} | |
} | |
Object.observe(obj, function(changes){ | |
var i = changes.length; | |
while(i--) { | |
var change = changes[i]; | |
// console.log(change.type, change.name, change.oldValue); | |
if (change.type === 'add') { | |
var addedObj = change.object[change.name]; | |
if (isObject(addedObj)) { | |
console.log("Observing new property because it is an object " + change.name ); | |
recourse(addedObj, change.name); | |
} | |
}else if (change.type === 'delete') { | |
console.log("delete"); | |
} else if(change.type === 'update'){ | |
if (typeof change.oldValue === 'object') { | |
} | |
var changed = change.object[change.name]; | |
if (isObject(changed)) { | |
recourse(changed, change.name); | |
} | |
console.log("update"); | |
} | |
} | |
if (!notifier) { | |
CB.apply(obj, arguments); | |
} | |
}); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment