简体   繁体   中英

Ember #<Object> has no method 'set'

I'm extracting JSON data in my routes as follows:

App.CollectionRoute = Ember.Route.extend({
 setupController: function(controller, model){
    $.getJSON('../returnitems.json', function(data){
      controller.set('returnItems', data);
    })
 }
});

Which gives me an object I can iterate over in my template with:

{{#each destination in controller.returnItems}}

Now I want to remove something via a controller with the following code:

this.get('controllers.collection').get('returnItems')[returnIndex].set('hasItems', false);

Which gives the following error:

Uncaught TypeError: Object #<Object> has no method 'set' 

But when I use: this.get('controllers.collection').get('returnItems')[returnIndex].hasItems = false

it tells me to use get and set?!

You shouldn't be doing AJAX calls in the setupController hook. You should use the model and the afterModel hooks so that Ember waits until the promise succeeds before fully transitioning to the route.

Now, you can't call the set method because $.getJSON returns an array of Plain Old Javascript Objects instead of the array of Ember.Object s you're expecting.

Instead you'd do something like this:

App.CollectionRoute = Ember.Route.extend({
 afterModel: function(controller, model) {
    var self = this;
    return $.getJSON('../returnitems.json', function(data_items){
        var items = [];
        for (var i = 0; i < data_items.length; i++) {
            items.push(Ember.Object.create(data_items[i]));
        }
        self.set('returnItems', items);
    });
 },
 setupController: function (controller, model) {
    controller.set('returnItems', this.get('returnItems'));
 }
});

Then you'd be able to:

this.get('controllers.collection').get('returnItems').objectAt(returnIndex).set('hasItems', false);

I hope this helps you!

Try to use

this.get('controllers.collection').get('returnItems').objectAt(returnIndex).set('hasItems', false); 

see: http://emberjs.com/api/classes/Ember.Array.html#method_objectAt

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