backbone.js - 获取额外的数据和请求 [英] backbone.js - getting extra data along with the request

查看:21
本文介绍了backbone.js - 获取额外的数据和请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一些用户的集合.需要的一些信息是总共有多少、多少页等.我如何将这些传回给客户端?或者它们是否必须来自一个单独的视图,在这种情况下我将需要多个 ajax 调用?我想要集合 fetch() 并接收一些元数据".处理这个问题的好方法是什么?

I have a collection which holds some of the users. Some information that is needed is how many total there are, how many pages, etc. How do I pass these back to the client? Or do they have to come from a separate view in which case I will need more than one ajax call? I'd like to have the collection fetch() and also receive some of this "meta data". What's a good way for handling this?

推荐答案

通常,您需要在集合类的 parse 方法中处理此问题.它的职责是接收响应并返回一组模型属性.但是,如果您不介意 parse 方法承担此额外责任,您可以做更多的事情.

Generally, you need to handle this in the collection class' parse method. Its responsibility is to take the response and return back an array of model attributes. However, you could do more than that if you wished if you didn't mind the parse method having this additional responsibility.

UserList = Backbone.Collection.extend({

    model: User,

    url: '/users',

    parse: function(data) {
        if (!data) {
            this.registered_users = 0;
            return [];
        }
        this.registered_users = data.registered_users;
        var users = _(data.users).map(
            function(user_data) {
                var user = {};
                user['name'] = user_data.name;
                return user;
            }
        );
        return users;
    }
});

因此在上面的简单示例中,假设服务器返回一个响应,其中包含注册用户的计数和用户属性数组.您将解析并返回用户属性,然后选择注册用户数并将其设置为模型上的变量.
parse 方法将作为 fetch 的一部分被调用.所以不需要修改fetch,直接使用自带的hook方法即可.

So in the trivial example above, presume the server returns a response which contains a count of registered users and and an array of user attributes. You would both parse through and return the user attributes and you would pick off the registered user count and just set it as a variable on the model.
The parse method would get called as part of a fetch. So no need to modify the fetch, just use the built-in hook method that you have.

纯粹主义者会说你给了 parse 方法一个次要的责任,这可能会让一些人感到惊讶(例如,返回一些东西和修改模型状态).不过,我认为这没关系.

Purists would say that you are giving the parse method a secondary responsibility which might surprise some people (e.g. returning something and modifying model state). However, I think this is okay.

这篇关于backbone.js - 获取额外的数据和请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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