Wednesday, 22 April 2015

Object.observe()

var model = {};
// Which we then observe
Object.observe(model, function(changes){
// This asynchronous callback runs
changes.forEach(function(change) {
// Letting us know what changed
console.log(change.type, change.name, change.oldValue);
});
});
Object {}
model.name = "yannos"
VM159:11 add name undefined
"yannos"
model.name = "yannis"
VM159:11 update name yannos
"yannis"
// If you don’t specify a list of accept types to O.o(), it defaults to the "intrinsic"
// object change types ("add", "update", "delete", "reconfigure", "preventExtensions"
// (for when an object becoming non-extensible isn’t observable)).
// Like earlier, a model can be a simple vanilla object
var model = {
name: 'yannis',
surname: 'kolovos'
};
// We then specify a callback for whenever mutations
// are made to the object
function observer(changes){
changes.forEach(function(change, i){
console.log(change);
})
};
// Which we then observe, specifying an array of change
// types we’re interested in
Object.observe(model, observer, ['delete']);
// without this third option, the change types provided
// default to intrinsic types
model.name = 'yannos';
// note that no changes were reported
VM562:4 "yannos"
delete model.name
VM562:4 Object {type: "delete", object: Object, name: "name", oldValue: "yannos"}
true
view raw gistfile1.js hosted with ❤ by GitHub

No comments:

Post a Comment