Ember.js Query Parameters

History and state

Elte Hupkes / eltehupkes@srxp.com

Hey!

Elte Hupkes (eltehupkes@srxp.com)

SRXP

Query params

/expenses?sort=date&filter=drinks

The issues

Model (Route) vs. Controller

Query string

/we/have/many/routes?yet=only_one_query_string

/not;all=servers/support;matrix=parameters

Homemade solutions

  • ember-query (Alex Speller)
  • ember-query-params (Elte Hupkes)

Native Implementation

Native Implementation 2.0

Controller ♥ Query params

App.SortedPostsController = Ember.ArrayController.extend({
    queryParams: ['sortVar:sort', 'page'],
    sortVar: 'date:desc'.
    page: 1
});

Controller ♥ Route

App.PostsRoute = Ember.Route.extend({
    // Flexible controller name
    controllerName: 'sortedPosts',

    // Hooks receive params
    model: function(params, transition) {
        console.log(params.sort); // date:asc
        console.log(params.page); // 1
    }
});

Optional refresh

App.PostsRoute = Ember.Route.extend({
    queryParams: {
        sort: { refreshModel: true }
    }

    // Alternatively
    actions: {
        queryParamsDidChange: function(changed, all, removed) {
            if ('sort' in changed) {
                // Awesome new refresh method!
                this.refresh();
            }
        }
    }
});

Defaults

controller.set('sortVar', 'date:desc');
// URL: /posts?sort=date:desc

controller.set('sortVar', 'date:asc');
// URL: /posts

Types

// URL: /posts?page=3
console.log(typeof controller.get('page')); // "number"

/?query=

Elte Hupkes / eltehupkes@srxp.com