How can I trigger an event handler when a property changes?

S

Sam Kong

Hi,

I want to trigger an event handler when a property changes.
If the property is set via a function, it's simple to trigger the
attached event handler.
But if the property is set directly, I don't know how.
What I want is like the property in C#.

var obj = new MyClass;
obj.onNameChange = function() {...}
obj.name = "Sam"; //<= I want to triger obj.onNameChange automatically.

If this is via a function:

var obj = new MyClass;
obj.onNameChange = function() {...}
obj.setName("Sam"); //<= I can trigger an event handler in the
function.


I hope I described what I want well.

Thanks.

Sam
 
M

Martin Honnen

Sam said:
var obj = new MyClass;
obj.onNameChange = function() {...}
obj.name = "Sam"; //<= I want to triger obj.onNameChange automatically.

Spidermonkey, the JavaScript engine used in Mozilla supports getter and
setter functions e.g. a setter for the |name| property with

function MyClass () {}
if (typeof MyClass.prototype.__defineSetter__ != 'undefined') {
MyClass.prototype.__defineSetter__(
'name',
function (value) {
alert('Setter called with "' + value + '".');
return value;
}
);
}

var obj = new MyClass();
obj.name = 'Kibo';

But you can't use that on the Web as other implementations (e.g. MS
JScript or Opera's engine) do not support __defineSetter__. So unless
you write extensions for Mozilla or script in another environment where
Spidermonkey is used as the JavaScript engine you don't have
getters/setters.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top