tags:

views:

78

answers:

2

Is it possible to create a property on a javascript object that behaves similar to a property in C#.

Example: I've created an auto-sizing textarea widget using dojo. In order to get the "value" property out of my widget, I've hooked up to the onchange event and I'm setting a variable everytime the value of the textarea changes.

Is there a way to accomplish this without hooking up to the onchange event.

Edit

In other words, is it possible to write something in JavaScript that behaves like getters and/or setters.

A: 

I'm not sure what you're asking here. You can always get the value of a textarea without the onchange event. you'd have to get the object then look at the value property.

for example, if your textarea has an id="mytext" you can do

var mytextarea = document.getElementById("mytext");
var text = mytextarea.value;
John Boker
That much I know John. Thank you. I've edited my question. I hope it is a little more clear now.
Seattle Leonard
it doesn't seem any clearer to me. Are you looking to add logic to the property getter and setter?
Davy8
That's exactly it
Seattle Leonard
+4  A: 

The short answer is no, but there will be in future. The recent ECMAScript 5 spec adds standardized getters and setters, and this will be implemented in browsers in the near future. IE 8 already has this feature, but only on DOM nodes. This is what the syntax looks like:

var obj = {};

Object.defineProperty(obj, "value", {
    get: function () {
        return this.val;
    },
    set: function(val) {
        this.val = val;
    }
});

There has been a proprietary implementation of getters and setters in Mozilla for a long time that was also later adopted by WebKit and Opera but this is not available in IE. The ECMAScript 5 implementation will be adopted by all browsers. Here's an ECMAScript 5 compatibility table that may be of interest: http://kangax.github.com/es5-compat-table/

Tim Down