简体   繁体   中英

Ember controller set property in action

New to ember and this is super dumb but I've wasted my day on it.

I'm creating an array of objects in my controller which i'm using to building radio buttons in my view.

when the button is clicked, i want to toggle the clicked attribute on the radio input so that it will appear clicked. Very simple but Ember keeps throwing me errors.

here's my code (edited some typos):

IndexController = Ember.ObjectController.extend({
    radioArray : function () {
        var a = [], i = 0;
        while (a.push({ index: i++, clicked: false }), i <= 10);
        return a;
    }.property('radioArray'),

    actions : {
        assignClick : function (item, index) {
             this.toggleProperty(item.clicked);

             // some unrelated business logic here
        }
    }
});

this hooks up to:

{{#each radioArray}}
    <label {{action "assignClick" this index}}>
        <input type="radio" {{bind-attr value=index checked=clicked}} /> foo
    </label>
{{/each}}

All i want is to show that the correct radio button has been clicked. But when i try and set clicked to true in my ctrl, i get "Uncaught Error: Assertion Failed: Cannot call get with false key."

If you're trying to use Em.Object.toggleProperty , then you need Em.Object . :) There are functions like Em.get and Em.set , which you can use for ember and non-ember objects, but there is no function Em.toggleProperty for a non-ember objects.

However, you can use Em.set with Em.get to implement toggle behavior:

Em.set(item, 'clicked', !Em.get(item, 'clicked'));

PS Setting property dependence from property itself doesn't make sense. (I'm talking about radioArray : function () {...}.property('radioArray') ).

PPS Working example: http://emberjs.jsbin.com/memuwi/2/edit?html,js,output

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM