Backbone.js - 我如何从集合中获取值?

时间:2013-12-27 07:47:36

标签: javascript jquery json backbone.js

我正在为我的项目使用jquery,backbonejs和underscorejs。 我的问题是,如何从给出的集合中获取值?

BranchModel

define([
  'underscore',
  'backbone'
], function(_, Backbone) {

  var BranchModel = Backbone.Model.extend({});

  return BranchModel;

});

BranchCollection

define([
  'jquery',
  'underscore',
  'backbone',
  'models/branch/BranchModel'
], function($, _, Backbone, BranchModel){
  var BranchCollection = Backbone.Collection.extend({
    model: BranchModel,
    url: "data.json",
        parse: function(data) {
            return data;
        }
  });

  return BranchCollection;
});

BranchView

define(['jquery', 'underscore', 'backbone', 'collections/branch/BranchCollection', 'text!templates/locate-us/mapTemplate.html'], function($, _, Backbone, BranchCollection, mapTemplate) {
    var MapView = Backbone.View.extend({
        el: $("#page"),
        initialize: function() {
            this.$el.off();
        },
        render: function(id) {
            var that = this;
            this.collection = new BranchCollection();
            var formValues = {
                id: id
            };
            this.collection.fetch({
                data: formValues,
                success: function(collection, response) {
                    that.$el.html(mapTemplate);
                },
                error: function() {
                    console.log("error");
                }
            });
        },
    });
    return MapView;
});

data.json

[
    {
      "id": "1",
      "name": "KCP KEBAYORAN LAMA, FMT-JKT",
      "address":"Jl. Raya Kebayoran Lama No. 22 (PAL VII), Kel. Sukabumi Utara - Kec. Kebon Jeruk, Jakarta Barat 11540",
      "latitude":"-6.1773997",
      "longitude":"106.8409396"
    },
    {
      "id": "2",
      "name": "KK JL. PANJANG, PDI-JKT",
      "address":"Jl. Panjang No 37 D, RT 006, RW 011, Kecamatan Kebon Jeruk, Kelurahan Kebon Jeruk, Jakarta Barat",
      "latitude":"-6.1632894",
      "longitude":"106.7633571"
    }
]

我想说,我想检索记录ID为1,所以我会得到这个值。

              "id": "1",
          "name": "KCP KEBAYORAN LAMA, FMT-JKT",
          "address":"Jl. Raya Kebayoran Lama No. 22 (PAL VII), Kel. Sukabumi Utara - Kec. Kebon Jeruk, Jakarta Barat 11540",
          "latitude":"-6.1773997",
          "longitude":"106.8409396"

提前多多感谢。

2 个答案:

答案 0 :(得分:1)

您似乎需要按id获取模型,因此您需要在urlRoot中提供model。例如:

var BranchModel = Backbone.Model.extend({
 urlRoot : '/branch'
});

这意味着您必须在Rest API

中拥有分支资源的网址
/branch        // returns all branches
/branch/:id    // returns a single branch that has this id

现在您可以按{<1}}开始提取模型,如下所示

id

希望这有用。

答案 1 :(得分:0)

你的意思是this.collection.get("1")

如果您的收藏集正确地从服务器获取值,您可以使用上面的代码获得所需的正确内容。