Skip to content

Instantly share code, notes, and snippets.

@andreiursan
Last active December 18, 2015 18:29
Show Gist options
  • Save andreiursan/5825603 to your computer and use it in GitHub Desktop.
Save andreiursan/5825603 to your computer and use it in GitHub Desktop.
This Gist is part of the talk "Manipulating Object Behavior at Runtime". that I had at http://www.meetup.com/gib-js/events/114764842/
/*
* WARNING: This code uses ECMAScript 6 features.
* today June 20, 2013, this works in Chrome only
* if you enable Javascript Experiments in your
* chrome flags settings.
*/
/*
* This is not a full implementation of the presented/idea
* Component Carcass
* should be treated as:
* "what hacks can I do with Proxy Object in ECMAScript 6"
*
*/
var ComponentCarcass = (function(){
function Components() {
// here we store the "behavior"
this.components = [];
this.addComponent = function(comp) {
this.components.push(comp);
}
this.allComponents = function() {
return this.components;
}
this.setValue = function(name, value) {
for (var i = 0; i < this.components.length; i++){
if(this.components[i].hasOwnProperty(name)){
this.components[i][name] = value;
return undefined;
}
}
}
this.getValue = function(name) {
for (var i = 0; i < this.components.length; i++){
if(this.components[i].hasOwnProperty(name)){
return this.components[i][name];
}
}
return undefined;
}
}
var components = new Components();
return Proxy.create({
get: function(receiver, name){
// also function calls are trapped by get
if(typeof components[name] === "function"){
return components[name].bind(components);
}
return components.getValue(name);
},
set: function(receiver, name, value){
components.setValue(name, value);
return true;
}
});
});
/*
* Example of a View Component
*/
function View(x, y){
this.x = x;
this.y = y;
this.draw = function(){
console.log("I'm drawing " + x + ", " + y);
}
}
/*
* Example of a Score Component
*/
function Score(score){
this.score = score;
}
<!DOCTYPE html>
<html>
<title>Dynamic Components</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<script src="component_carcass.js"></script>
<script>
function init(){
var cc = ComponentCarcass();
cc.addComponent(new View(2, 2));
// trapped get
console.log("cc has a x property, of value " + cc.x);
console.log("cc has a y property, of value " + cc.y);
// trapped set
cc.x = 22;
console.log("now x is " + cc.x);
// adding a new component to the carcass
cc.addComponent(new Score(100));
console.log("component score: " + cc.score);
console.log("component has x: " + cc.x);
console.log("component has y: " + cc.y);
}
window.onload = init;
</script>
<body>
<h1>Open the console and Proxy!</h1>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment