简体   繁体   中英

Sharing data between controllers in Ember

I'm new to Ember and I'm pulling my hair out over this.

The app I'm working on has a set of "alerts" that will be dynamically updated. I have the alerts template/controller/module all working fine. The alerts controller has a method for displaying the number of alerts that have not been dismissed. This works fine within the alerts template.

However, when I access that same method from another controller, it always returns 0.

Here's a pastebin with the controllers, templates and model

Thanks for any help!

UPDATE :

I discovered that if I actually load the alerts view, and then go back to the home view, the alerts controller starts returning the correct value. So apparently there is an issue with the fixture data not being ready when the menu controller accesses that method. I haven't yet been able to figure out why.

Try something like this:

App.HomeRoute = Ember.Route.extend({
    renderTemplate: function(controller, model) {
        this._super(controller, model);
        this.render('menu', {
            into: 'home',
            outlet: 'alertsMenuItem',
            controller: 'alerts'
        });
    }    
});

<script type="text/x-handlebars" data-template-name="home">
    <img {{bind-attr src=appInfo.headerImage}} id="header_image" alt="Header Image" />
    {{render "alerts" model}}
    <ul id="home_nav">
        <li>Home</li>
        <li>About</li>
        <li>
            {{outlet "alertsMenuItem"}}
        </li>
    </ul>
</script>   

<script type="text/x-handlebars" data-template-name="menu"> 
    {{#link-to 'alerts'}}
        Alerts ({{remaining}})
    {{/link-to}}
</script>

with Ember.Route.render you can specify the controller to use for a template.

Note that if you want to access your AlertsModel from routes other than alerts , you should set up your model in the AlertsController instead. Something like this works for me with Ember 1.10, but might be slightly different for earlier version:

App.AlertsController = Ember.ArrayController.extend({
    init: function() {
        var self = this;
        this.store.find('alert').then(function(model) {
            self.set('model', model);
        });
    },
    sortProperties: ['createdAt:desc'],
    sortedModel: Ember.computed.sort("model", "sortProperties"),
    remaining: function() {
            console.log(this.filterBy('isCompleted', false).get('length'));
            return this.filterBy('isCompleted', false).get('length');
    }.property('@each.isCompleted')
});

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