Search code examples
ember.jsember-router

Emberjs router with partially interpreted route


I want to create something similar to what Stackoverflow has with the share button: I want to create a short link for shares. Now my link can take the following 3 forms:

s/51b9dd49065f905411000000/1
s/51b9dd49065f905411000000/51b9dd49065f905411000020/2
s/51b9dd49065f905411000000/51b9dd49065f905411000020/51b9dd49065f905611000020/3

How can I make ember to interpret the route only until s/ then give me the rest as some argument so I can process it and reconstruct the proper route?


Solution

  • You can use star segments. This is documented here

    Given this application:

    App.Router.map(function() {
        this.route('share', { path: 's/*linkPath' })
    });
    
    App.ShareRoute = Ember.Route.extend({
      model: function(params) {    
        console.log(params.linkPath);
        return params;
      }
    });
    

    When a url begins with s/ and ends with anything. The remaining value will be setup in a variable called linkPath.

    For example:

    URL                          => params.linkPath content    
    -------------------------------------------------------------
    s/51b9dd49065f905411000000/1 => "51b9dd49065f905411000000/1"
    s/hey/ho/lets/go             => "hey/ho/lets/go"
    

    So in your model hook, you can get the rest of the arguments, using params.linkPath.

    You can see this in action in that jsbin http://jsbin.com/OrEhAso/3/#/s/51b9dd490/51b9dd490/3. Open the console and you will se the string "51b9dd490/51b9dd490/3" logged.