2

I have a computed property that builds an array from another attribute and returns it. When I update this array with addObject, set is obviously not called so I cannot update the orignal attribute. Is there a way for me to also update the original attribute on addObject or removeObject ?

In this example, I build an array from a string of comma separated values:

App.MyModel = DS.Model.extend({

    someAttribute: DS.attr('string'),

    computed: function(key, value) {
        var computedArray,
            someAttribute;

        // getter
        if (arguments.length === 1) {
            someAttribute = this.get('someAttribute');
            computedArray = description.split(',');
            return Ember.A(computedArray);
        }
        // setter
        else {
            someAttribute = value.join(',');
            this.set('someAttribute', someAttribute);
            return value;
        }
    }.property('someAttribute')

});

Now if I update my computed property like this, it works as expected:

>>> model.set('computed', ['turtles', 'all', 'the', 'way', 'down'])
['turtles', 'all', 'the', 'way', 'down']
>>> model.get('someAttribute')
"turtles,all,the,way,down"

But now if I do it this way, they are (expectedly) not synchronized:

>>> model.get('computed').addObject('oh yeah')
['turtles', 'all', 'the', 'way', 'down', 'oh yeah']
>>> model.get('someAttribute')
"turtles,all,the,way,down"

To generalize my question: is it possible to keep in sync a computed property with the attributes used to compute it when the computed property is mutable? And if not, is there a workaround for arrays (Ember.A())?

I'm new to Ember and there is probably stuff going on under the hood that I don't know about yet, but please enlighten me ;)

1 Answer 1

2

This is probably by design given that computed properties are also cached by default. So even if you manage to get this working, binding against such properties would be problematic.

Nevertheless, You might have some luck with setting up a secondary observes function that then watches the computed property. You will also need to back your computed property with a fixed array, unlike the new array you return on each getter.

Unless it's something critical, I would avoid going against the Ember conventions.

"If once you start down the dark path, forever it will dominate your destiny" :)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I guess ember is not the best tool if the difference between your API and your client side model is too important and you don't have control over it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.