0
votes

How can I add additional model properties after I find a model? (Or how can I access a route's params in setupController?

given a route

   this.resource('gallery', { path:'/gallery/:gallery_id' });

and a router /routes/gallery.js

export default Ember.Route.extend({
    model: function(params) {
        return this.store.find('monkeys', { monkeyType: params.gallery_id });
        //can I add an additional property to the returned model here?
    },

    setupController: function(controller, model) {
        var pageTitle = 'something related to params.gallery_id';
        //can I access route params in here?
        this.controllerFor("application").set('pageTitle', pageTitle);
        controller.set('model', model);
    }
});

Ideally I want to set the pageTitle property on the application controller to some gallery_id specific string, which is not returned by the api service.

the api returns the following, based on the url /monkeys?monkeyType=someId

{ "monkeys":[{ ... }, { ... }] }
2

2 Answers

1
votes

Maybe something like this?

export default Em.Route.extend({
    model: function(params) {
        var model = this.store.find('monkeys', { monkeyType; params.gallery_id });

        model.then(function(models) {
            this.controllerFor('application').set('pageTitle', models.get('firstObject.name'));
        }.bind(this));

        return model;
    }
});

Make sure you're returning model and not the promise returned by the then call. store.find() returns a PromiseArray while then() just returns a promise.

0
votes

Here's what I've ended up with:

export default Ember.Route.extend({
    model: function(params) {
        return return {
            tag:params.gallery_id,
            monkeys:[]
        };
    },
    setupController: function(controller, model) {
        var url = window.ENV.api + 'monkeys?monkeyType=' + model.tag;

        if(model.monkeys.length === 0){
            $.getJSON(url, function(json){
                model.monkeys.pushObjects(json.monkeys);
            });
        }

        this.controllerFor("application").set('pageTitle',
             this.getTitle(model.tag));

        controller.set('model', model);
    },
    getTitle: function(tag){
        //some arbitrary non-api lookup
    }
});

I'm not too keen on this solution, so would be happy to hear of improvements, or perhaps a version that makes use of Ember Data.