【问题标题】:Backbonejs - How can I print the results of a fetch?Backbonejs - 如何打印提取结果?
【发布时间】:2014-01-14 03:28:27
【问题描述】:

您好,我是 Backbone 的新手,我只是玩了一下,这是我的代码:

    var Users = Backbone.Collection.extend ({
        url : 'http://backbonejs-beginner.herokuapp.com/users'
    });

    var users = new Users();
    users.fetch({
        success: function () {
            console.log(users);
        }
    });

fetch 调用成功,我返回一个如下所示的对象:

[
  {
    "id": "hqel839m1071rbggsxf7",
    "firstname": "Thomas",
    "lastname": "Davis",
    "age": 12
  }
]

如何打印结果的不同部分? 例如我想打印第一项的“id”参数。我可以像数组一样迭代它吗?

我尝试过console.log(users[0].id),但它不起作用。

谢谢。

【问题讨论】:

    标签: javascript json backbone.js dto


    【解决方案1】:

    不要忘记arguments 传递给collection.fetchsuccess 回调,它们是(collection, response, options)。检查文档here。您可以使用collection 参数来选择特定的model。检查以下代码:

    var Users = Backbone.Collection.extend ({
        url : 'http://backbonejs-beginner.herokuapp.com/users'
    });
    
    var users = new Users();
    users.fetch({
        success: function (collection, response, options) {
            //Will log JSON objects of all User objects
            console.log(collection.toJSON());
            //You can get a Model using 'id'
            var user = collection.get("hqesig1ea1br2k6horay");
            // Will log User Model for id "hqesig1ea1br2k6horay"
            console.log(user);
            //You can then fetch Model attributes this way
            console.log("ID: ", user.get('id'));
            console.log("First name: ", user.get('firstname'));
            console.log("Lastname : ", user.get('lastname'));
        }
    });
    

    fiddle 供您参考。

    【讨论】:

      【解决方案2】:

      可以通过三种不同的方式访问Backbone.Collection 中的模型。首先,您可以使用.get 方法根据其唯一ID 查找模型。这基本上会查看集合中的所有模型,并将它们的 id 属性与提供的属性进行比较。

      var user = collection.get('unique_id'); // return an instance, or null
      

      第二种方法是使用.at方法通过索引获取模型。如果您的模型已排序,这将很有用。如果它们没有排序,它们将按插入顺序(即它们被提供给集合的顺序)获取:

      var user = collection.at(0); // return the first model in the collection
      

      最后,您可以访问 Collection 包装的模型的原始数组。您可以通过 .models 属性访问它,它只是一个数组。这不是推荐的方法。

      var user = collection.models[0];
      

      拥有用户后,您可以通过模型上的.get 方法访问用户的任何属性:

      var age = user.get("age");
      user.set("age", 100);
      

      您可以查看模型get 方法here 的文档,以及Backbone.Collection here 的文档。

      【讨论】:

      • 当我尝试执行 console.log(users[0].get("id"));
      • 对不起,我编辑了我的答案,我忘记了模型数组。我链接的内容现在可以使用了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-26
      • 2021-07-10
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 2021-08-11
      相关资源
      最近更新 更多