Properties not writable

40 views
Skip to first unread message

samuelgo...@gmail.com

unread,
Mar 7, 2013, 6:59:56 AM3/7/13
to trai...@googlegroups.com
Hello,

I just started using traits.js.

I've found that the properties of the objects I compose are being left as non-writable.

I'm interested in being able to write them. Well, not all of them, but a few in particular.

Is this read-only mode a bug of the library, or may there be something that I don't understand about traits or the library itself?

Thank you very much.

Tom Van Cutsem

unread,
Mar 7, 2013, 11:48:04 AM3/7/13
to trai...@googlegroups.com
Hi,

This is not a bug in the library, but is very much intentional.

Basically, the Trait.create function will automatically "freeze" your object, which includes making all fields non-writable.

If you don't want the library to do this, you can use Object.create rather than Trait.create to create your objects. Objects created with Object.create will still have writable fields.

For more details about how this works, check out the howtonode article on traits.js:

Another alternative is to define getters and setters that update some other variable, e.g.:

function makeTrait(fooState) {
  return Trait.create({
    get foo() { return fooState; },
    set foo(v) { fooState = v; }
  });
}
var obj = makeTrait(42);
obj.foo // 42
obj.foo = 24
obj.foo // 24

Cheers,
Tom
Reply all
Reply to author
Forward
0 new messages