backbone.js - 随请求获取额外数据

发布于 2024-11-02 04:54:23 字数 147 浏览 0 评论 0 原文

我有一个包含一些用户的集合。需要的一些信息是总共有多少页,有多少页等。我如何将这些信息传递回客户端?或者它们是否必须来自单独的视图,在这种情况下我将需要多个 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

时光匆匆的小流年 2024-11-09 04:54:23

一般来说,你需要在集合类的解析方法中处理这个问题。它的职责是获取响应并返回模型属性数组。但是,如果您愿意,如果您不介意 parse 方法承担此额外责任,您可以做更多的事情。

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

因此,在上面的简单示例中,假设服务器返回一个响应,其中包含注册用户的计数和用户属性的数组。您将解析并返回用户属性,然后选择注册用户数并将其设置为模型上的变量。
解析方法将作为获取的一部分被调用。因此无需修改 fetch,只需使用您拥有的内置钩子方法即可。

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

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

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.

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.

川水往事 2024-11-09 04:54:23

实现此目的的一种方法是重写 Collection::fetch() 方法,以便它从响应中解析此元数据。您可以让后端返回如下响应:

{
    "collection": [
        { ... model 1 ... },
        { ... model 2 ... },
        ...
    ],
    "total_rows": 98765,
    "pages":      43
}

在覆盖原始 Backbone.Collection::fetch() 方法的 fetch 方法中,您可以处理分别对象。您可以使用稍加修改的 fetch 方法进行覆盖:

_.extend(Backbone.Collection.prototype, {
  fetch : function(options) {
    options || (options = {});
    var collection = this;
    var success = options.success;
    options.success = function(resp) {
      // Capture metadata
      if (resp.total_rows) collection.total_rows = resp.total_rows;
      if (resp.pages)      collection.pages      = resp.pages;

      // Capture actual model data
      collection[options.add ? 'add' : 'refresh'](
        collection.parse(resp.collection), options);

      // Call success callback if necessary
      if (success) success(collection, resp);
    };
    options.error = wrapError(options.error, collection, options);
    (this.sync || Backbone.sync).call(this, 'read', this, options);
    return this;
});

请注意,使用 _.extend 的这种方法将影响扩展 所有 的类代码>Backbone.Collection。

这样,您就不必对后端进行两次单独的调用。

One way to do this is to override the Collection::fetch() method so that it parses this metadata out of the response. You could have your backend return a response like this:

{
    "collection": [
        { ... model 1 ... },
        { ... model 2 ... },
        ...
    ],
    "total_rows": 98765,
    "pages":      43
}

In your fetch method which overrides the original Backbone.Collection::fetch() method, you can handle each property of the object separately. Here's you could do the override with a slightly modified fetch method:

_.extend(Backbone.Collection.prototype, {
  fetch : function(options) {
    options || (options = {});
    var collection = this;
    var success = options.success;
    options.success = function(resp) {
      // Capture metadata
      if (resp.total_rows) collection.total_rows = resp.total_rows;
      if (resp.pages)      collection.pages      = resp.pages;

      // Capture actual model data
      collection[options.add ? 'add' : 'refresh'](
        collection.parse(resp.collection), options);

      // Call success callback if necessary
      if (success) success(collection, resp);
    };
    options.error = wrapError(options.error, collection, options);
    (this.sync || Backbone.sync).call(this, 'read', this, options);
    return this;
});

Note that this approach using _.extend will affect all your classes which extend Backbone.Collection.

This way, you don't have to make 2 separate calls to the backend.

寄人书 2024-11-09 04:54:23

我会在页面创建时引导信息。服务器创建站点时将信息写入html文档中。这样你就根本不需要进行 ajax 调用。我对整个集合执行此操作,以免首先加载页面,然后等待 ajax 调用返回所需的信息。

使用 Python 的代码示例:

第 64 行: https://github.com/ichbinadrian /maps/blob/master/python/main.py <- 从这里开始

第 43 行:https://github.com/ichbinadrian/maps/blob/master/templates/index.html <- 进入此处

I would bootstrap the information at pagecreation. Write the information into the html document when the server creates the site. Like that you don't have to have an ajax call at all. I do that with the whole collection in ordner not to first load the page and then wait for the ajax call to return the information needed.

Code example with Python:

Line 64: https://github.com/ichbinadrian/maps/blob/master/python/main.py <- from here

Line 43: https://github.com/ichbinadrian/maps/blob/master/templates/index.html <- into here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文