简体   繁体   中英

Ember.js (pre4) array controller not keeping state

Edit 2013-03-02

This appears to be resolved in RC1


In previous versions of Ember.js, controllers would keep state assigned to them, but this seems to be an issue in Pre4.

So if I were to have this controller

App.UsersController = Ember.ArrayController.extend({
    content: ['mike', 'jen', 'sofia'],

    _content_observer: (function(){
         /* I'm called, but my author doesn't know why */
         console.log('Content was altered! But why? And by whom?');
    }).observes('content')
});

The content is overwritten for some unexplained reason. I don't want to use ember data , but it seems like I'm being forced that direction.

This JS Fiddle exemplifies the issue.

What's going on? How do I stop it or is this so engrained in embers opinionatedness that I need to just accept it and go with the flow?


Edit

Taking this a bit further, it appears that whatever is setup as the model will be set to the content value, even if you override the setupController hook.

eg:

UsersRoute = Ember.Route.extend({
    model: function() {
        /*I should never be called, but I am. How curious.*/
        return ['This','Shouldnt','Be','Assigned'];
    },
    setupController: function() {
        /* According to http://emberjs.com/guides/routing/specifying-a-routes-model/, I should prevent the model from being assigned to content, but I don't */
    }
});

The UsersController.content will end up with the value ['This','Shouldnt','Be','Assigned']

See this updated fiddle

This isn't really an ember-data thing. The new router sets controller's content property automatically. Instead of setting content from within the controller dedinition, customize the model that will be used for your route by overriding the model hook. For example:

App.UsersRoute = Ember.Route.extend({
    model: function() {
      return ['mike', 'jen', 'sofia', 'greta']
    }
}

I modified your jsfiddle here: http://jsfiddle.net/WGYmg/

You may use the setupController method to set the controller's contents as you like:

setupController: function(controller) {
    controller.set('content', []);
}

See this fiddle

Edit

You can use the model method to return the original content:

model: function () {
    var c = this.controllerFor('users');
    return c.get('content');
}

This is a bit hackish, but still..:)

See updated fiddle

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