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

disbfnqx  于 2024-01-07  发布在  jQuery
关注(0)|答案(2)|浏览(176)

我在我的项目中使用jquery,backbonejs和underscorejs。我的问题是,我如何从给定的集合中获取值?
分支模型

  1. define([
  2. 'underscore',
  3. 'backbone'
  4. ], function(_, Backbone) {
  5. var BranchModel = Backbone.Model.extend({});
  6. return BranchModel;
  7. });

字符串
分支集合

  1. define([
  2. 'jquery',
  3. 'underscore',
  4. 'backbone',
  5. 'models/branch/BranchModel'
  6. ], function($, _, Backbone, BranchModel){
  7. var BranchCollection = Backbone.Collection.extend({
  8. model: BranchModel,
  9. url: "data.json",
  10. parse: function(data) {
  11. return data;
  12. }
  13. });
  14. return BranchCollection;
  15. });


BranchView

  1. define(['jquery', 'underscore', 'backbone', 'collections/branch/BranchCollection', 'text!templates/locate-us/mapTemplate.html'], function($, _, Backbone, BranchCollection, mapTemplate) {
  2. var MapView = Backbone.View.extend({
  3. el: $("#page"),
  4. initialize: function() {
  5. this.$el.off();
  6. },
  7. render: function(id) {
  8. var that = this;
  9. this.collection = new BranchCollection();
  10. var formValues = {
  11. id: id
  12. };
  13. this.collection.fetch({
  14. data: formValues,
  15. success: function(collection, response) {
  16. that.$el.html(mapTemplate);
  17. },
  18. error: function() {
  19. console.log("error");
  20. }
  21. });
  22. },
  23. });
  24. return MapView;
  25. });


data.json

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


比如说,我想检索记录id no 1,所以我将得到这个值。

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


多谢了。

1u4esq0p

1u4esq0p1#

似乎你需要通过id获取模型,为此你需要在你的model中提供一个urlRoot。例如:

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

字符串
这意味着您必须在Rest API中拥有分支资源的url。

  1. /branch // returns all branches
  2. /branch/:id // returns a single branch that has this id


现在可以开始通过id获取模型,如下所示

  1. var model = new BranchModel({id:someId});
  2. model.fetch();


希望这对你有帮助。

展开查看全部
i1icjdpr

i1icjdpr2#

你是说this.collection.get("1")
如果你的集合正确地从服务器获取了值,你就可以用上面的代码得到你想要的东西。

相关问题