Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save hernan/5bba9e1716482fc180db to your computer and use it in GitHub Desktop.
Save hernan/5bba9e1716482fc180db to your computer and use it in GitHub Desktop.
// Little background about unknown properties
var myObject = Ember.Object.create({name: 'hi'}); # a plain simple ember object
// so the property "name" is a known property for myObject, but any other properties which are not defined on this object are unknown properties
myObject.get("age"); // age is an unknown property as we did not set "age" yet, the expression on the left evaluates to undefined
// Be careful ! only properties on the object that are not "set" yet are unknown properties but not the properties that evaluate to null/undefined
myObject.set("status", undefined); // although myObject.get("status") evaulates to undefined, status is a known property for myObject
// unknownProperty hook
// Basically when we do a "get" on a unknown property, instead of returning undefined the result of the unknownProperty hook is returned
var hookedObject = Ember.Object.create({
name: 'hi',
unknownProperty: function(key) {
return key+" is an unknown property";
}
});
hookedObject.get("name"); // => hi
hookedObject.get("randomKey"); // => randomKey is an unknown property
hookedObject.get("age"; // => age is an unknown property
hookedObject.set("age", 22); // age is now a known property
hookedObject.get("age"); // => 22
// setUnknownProperty hook
// it gets called when we are trying to do a set on an unknown property
var baseObject = Ember.Object.create();
var hookedObject = Ember.Object.create({
setUnknownProperty: function(key, value){
baseObject.set(key, value);
}
});
hookedObject.set("name", "Bruce");
baseObject.get("name"); // => Bruce
// We are basically proxying the set property to other object, Reminds you of something ?...Enter Ember.ObjectProxy
// `Ember.ObjectProxy` forwards all properties not defined by the proxy itself
// to a proxied `content` object. (from the source code)
// Let's implement a similar proxy object of our own using the above concepts
var myProxyObject = Ember.Object.create({
unknownProperty: function(key){
var content = this.get("content");
if(content){
return content.get(key);
}
},
setUnknownProperty: function(key, value){
var content = this.get("content");
if(content){
return content.set(key, value);
}else{
// raise an error saying cannot set key, value as the content property is undefined
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment