View Full Version : Custom Object "getter setter"

03-18-2007, 06:26 AM

Im building custom properties and its working fine:

var myDiv = document.createElement('div');
myDiv.__defineGetter__("_x", function() { return this.style.left; });
myDiv.__defineSetter__("_x", function(x) { this.style.left = x+'px'; });

but... only it only works in Mozilla type browsers. It doesn't work in Safari! Arrrg!

Doesn anyone know a hack?


03-18-2007, 09:49 AM
No, not really. Setters and getters aren't supported in a lot of browsers. You'll just have to use getX() and setX(newX).

03-18-2007, 04:04 PM
Yeah I'm using functions for this which work perfectly. Im sooo picky. ;)

There has so be some way (bescides using a setInterval, thats cheating) to do this. Maybe I'll dismantle the form onchanged method. Its a start :)

03-18-2007, 05:14 PM
Heres my first attempt:

It works great, but Im weary of the CPU setIntervals can consume.

Object.prototype.addProperty = function($prop, $getter, $setter) {
this[$prop] = "";
this.getter = $getter;
this.setter = $setter;
var _this = this;
this.listener = setInterval(function() {
if(_this[$prop] != _this.getter()) {
_this[$prop] = _this.getter()

Useage ::
// Object.addProperty(property:String, getter:Function, setter:Function);
myDiv.addProperty("_x",function() { return this.style.left; }, function(x) { this.style.left = x+'px';});

This could be a perfect solution without the setInterval. Any ideas?

03-18-2007, 05:23 PM
I don't understand what your problem is with JavaBeans-like getX() and setX(x).

03-18-2007, 08:00 PM
I dont have a problem with functions? I prob should of mentioned because it does sounds like over kill just to change syntax from _x() to _x, but its actually important to the project.

I'm a Flash designer/devleoper professionally and I wrote a JS class that allows you to write syntax just like Actionscript using javascript / AJAX. (Javascript with Actionscript Writing Syntax : "JAWS") Its really great and multi-browser-compatable. (except for the damn AS properties)

I did write them all as _x() _y() _alpha() etc.. which works, but its the only difference in syntax and I'm not stopping at 99% complete.

If I can't get a better method than the addProperty proto I wrote, I have a plan B.

03-18-2007, 10:27 PM
Ah, I see. Well... no, I don't think you're going to get much better than that, but I can see it leading to race conditions. I'm afraid you might have to admit defeat on this one.

03-19-2007, 12:22 AM
Race conditions?