Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of serialize hook in ember routes

Tags:

ember.js

What is the use of serialize hook in ember route class?

       App.PostRoute = Ember.Route.extend({
        model: function(params) {
            return this.store.find('post', params.post_id);
        },

        serialize: function(post) {
            return { post_id: post.get('id') };
        }
    });

Ember Documentation says:

If your dynamic segment ends in _id, the default model hook will convert the first part into a model class on the application's namespace (post becomes App.Post). It will then call find on that class with the value of the dynamic segment. The default serialize hook will pull the dynamic segment with the id property of the model object.

But i am not able to understand the use of serialize hook in route class

like image 369
Dhakchianandan Avatar asked Mar 21 '23 19:03

Dhakchianandan


1 Answers

The serialize method determines what to use as parameter for the provided entity.

Example.

Say you have the following user model, with the following properties.

id
username
email

Now if you have a list of users, and you want to link to a show user details page, you might use a loop like this.

{{#each users}}
  {{#link-to user.show this }} {{username}} {{/link-to}}
{{/each}}

So when Ember sees this link-to helper i will convert it to a link, which might look like this

<a href="/user/1">elvar</a>

Now the default behavior here is to use the id as a parameter, which is what your own example shows, i picks the id from the model. We can change this with the serializer method.

Lets say that instead of using the id, we want to use the username as a parameter.

App.UserShowRoute= Ember.Route.extend({
    model: function(params) {
        return this.store.find('user', params.user);
    },

    serialize: function(user) {
        return { user: user.get('username') };
    }
});

Now the link-to helper will yield the following instead.

 <a href="/user/elvar">elvar</a>
like image 155
MartinElvar Avatar answered Mar 28 '23 19:03

MartinElvar