So I wanted an object to have a reference to a string in side of an
array some where else and so here is how I made that possible:
<div id="something"> </div>
<script>
var obj = document.getElementById('something');
var vars = {
name : 'bob',
color : 'blue',
}
// the problem
obj.varRef = vars.name; // this copies the value not a ref
// so
obj.varRef = 'sam'; // this doesnt update vars.name
// my solution
/*
stringRef requires the following
- the reference your are making is inside of an object
- this is so we can use watch
- that you know the absolute call to the var you are referencing
- this is so we can use it in an eval
- and the name of the ref object we are creating
- but of course you would know this.
i realize a lot, but not all, of the many limitatons this has. got
any better ideas?
*/
document.stringRef = Class.create();
document.stringRef.prototype = {
initialize : function (parent, myname, ref) {
this.ref = ref;
var that = this;
parent.watch (myname, function (id,oldval,newval) {
eval( that.ref+' = "'+newval+'"' );
return that;
});
},
toString : function () { return eval(this.ref); },
};
// how to use it
obj.varRef = new document.stringRef( obj, 'varRef', 'vars.name' );
check();
vars.name = 'bob2';
check();
obj.varRef = 'paul';
check();
function check () {
document.writeln(
'vars.name : '+vars.name+'<br>'+
'obj.varRef : '+obj.varRef+'<br>'
);
}
</script>
any suggestions? thoughts?
I was bumbed i couldnt do this so i made something that worked but
maybe there is no need for this?
thanks