Creating a computed from outside of your class

I’m trying to create a service that has some private/scoped state. I’d like to expose this state as a readOnly or oneWay binding but I can’t seem to figure out how to do this unless the state object is part of the class, I.E like this:

init() {
    var internalVal = obj.create();
    this.__internalVal = internalVal;
    this.publicAlias = Ember.computed.readOnly('__internalVal.internalValue');

This, of course, defeats the purpose if you can still access __internalVal.

What I ended up with was using an observer:

init() {
    var self = this;
    var internalVal = obj.create();
	this.color = internalVal.get('internalValue');
    internalVal.addObserver('internalValue', function(sender) {
        self.set('color', sender.get('internalValue'));
    this.setColor = function(colorName) {
        internalVal.set('internalValue', colorName);

Is this the correct way to get the behavior i’m looking for, or is there some alternate syntax for computed that will allow me to do it using the macro? I tried having ‘obj’ declared a computed alias and then setting this.color to that property but it didn’t work right and or would only ever set it’s initial value.

Here’s a twiddle with the setup in case it’s not clear what I’m trying to do. Ember Twiddle

If you use volatile computed properties, you can completely avoid caching of your CPs, thus making sure that the returned value is fresh from your private object.

Besides, the new CP syntax introduced in Ember 1.12 allows for a much easier get/set behaviour.

I’ve fixed your Twiddle so it doesn’t use observers, that have been declared evil; read here and see @stefan here about observers.

Here’s the code.

EDIT: missing links… :-/

Hope this helps,

1 Like

That was a spectacularly educational set of links, thank you so much! I completely overlooked volatile in the API docs thinking it was some kind of internal thing.

This is exactly what I was looking for.