在余烬路线中使用序列化挂钩 [英] Use of serialize hook in ember routes

查看:58
本文介绍了在余烬路线中使用序列化挂钩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在余烬路由类中使用序列化钩子有什么用?

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说明文件:

Ember Documentation says:

如果您的动态段以_id结尾,默认的模型钩子会将第一部分转换为应用程序名称空间上的模型类(发布成为App.Post)。然后它将使用动态段的值在该类上调用find。
默认的序列化挂钩将使用模型对象的id属性拉动动态段。

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

推荐答案

serialize方法确定将什么用作提供的实体的参数。

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

示例。

假设您拥有以下具有以下属性的用户模型。

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}}

因此,当Ember看到此链接至帮助程序时,我会将其转换为链接,可能看起来像这样

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>

现在,这里的默认行为是使用id作为参数,这就是您自己的示例所显示的,我从模型中选择ID。我们可以使用序列化方法来更改它。

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.

让我们说,我们不想使用id,而是要使用用户名作为参数。

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>

这篇关于在余烬路线中使用序列化挂钩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆