当前位置: 首页 > 知识库问答 >
问题:

无法使用backbone.js正确获取集合

陈茂
2023-03-14

请读到最后(我在最后提到console.log)

模型:

// Spot model:
define([
  'jquery',    
  'underscore',
  'backbone'  
], function($, _, Backbone){
    var Spot = Backbone.Model.extend({
        url: function(){
            if (this.get('id') !== null){
                return '/spot/' + this.get('id');
            }
            return '/spots';
        },
        idAttribute: "id",
        defaults: {
            id: null,
            details:{
                name: "school",
                type: 4,
                rank: 3,
                comment: null
            },
            location:{
                    address: '',
                    lat: 70.345,
                    lng: 90.123
            },
            user:{
                id: 12345,
                name: "magneto"
            }
        },
        parse: function(response){
        /*  var attrs = {
                details: {},
                location: {},
                user: {}
            };
            attrs.id = response.id;

            attrs.details.name = response.details.name;
            attrs.details.type = response.details.type;
            attrs.details.rank = response.details.rank;
            attrs.location.lat = response.location.lat;
            attrs.location.lng = response.location.lng;
            return attrs; */
        }
    });
    return Spot;
});

收藏:

// Spots collection:
define([
  'jquery',    
  'underscore',
  'backbone',  
  'models/Spot'
], function($, _, Backbone,spot_model){
    var Spots = Backbone.Collection.extend({
        model: spot_model,
        url:
            function() {
            return '/projects/FE/spots';
          },
        parse: function(response){
    /*      var parsed = [],
              key;

          _.each(response, function (value) {
              parsed.push(value);
          }, this);

          return parsed;*/
        },
      comparator: function(spot){
        return spot.rank;
      }
    });
    return Spots;
});

观点:

// inside our view named: SpotsView
define([
  'jquery',
  'underscore',
  'backbone',
  'mustache',
  'icanhaz',
  'views/spots/Spot',
  'collections/Spots',
  'text!../../../../templates/spots/spots.mustache!strip',
], function($,
            _,
            Backbone,
            mustache,
            ich,
            SpotView,
            Spots,
            SpotsTemplate){
  var SpotsView = Backbone.View.extend({
    //el: $("#container"),
    tagName: "ul",
    initialize: function(){

      console.log('initialize view');
      console.log(this.collection);
      _.bindAll(this,'render');

    },
    render: function(){
      console.log(this.collection);
      console.log('length: ' + this.collection.length);
      console.log('models: ' + this.collection.models);

      _.each(this.collection.models, function (spot) {
            $(this.el).append(new SpotView({model:spot}).render().el);
        }, this);
      return this;
    }
  });
  return SpotsView;
});

在我们的应用程序中。js

   var spots = new Spots({model: Spot}),
        spotsview;


    spots.reset();
    console.log(spots.fetch());
    console.log('spots:');
    console.log(spots.length);
    console.log(spots);
    spotsview = new SpotsView({collection: spots});

服务器输出

// SERVER output(s) i tried:
{"id": 666,"details":{"name": "mark","type":4,"rank":3.1,"comment":"nothing"},"location":{"lat":70.123,"lng":90.321,"address":"5th avenue"},"user":{"id":333,"name":"wolverine"}}

// another one i tried:
[{"id": 666,"details":{"name": "mark","type":4,"rank":3.1,"comment":"nothing"},"location":{"lat":70.123,"lng":90.321,"address":"5th avenue"},"user":{"id":333,"name":"wolverine"}}]

// another one:
[{"id":"55","details":{"name":"Dan","type":"6","rank":"-9.9","comment":"myEx"},"location":{"lat":"40.780346","lng":"-73.957657","address":"78, West 86th Stree"}},{"id":"57","details":{"name":"Ron","type":"6","rank":"3.0","comment":"Butch"},"location":{"lat":"40.715569","lng":"-73.832428","address":"1344 Queens Boulevard"}},{"id":"58","details":{"name":"Monk's","type":"11","rank":"9.5","comment":"yesss"},"location":{"lat":"40.805443","lng":"-73.965561","address":"112th and broadway "}}]




// without using "parse" method in the collection and in the model (they are commented) i get:
d
_byCid: Object
_byId: Object
length: 0
models: Array[0]
__proto__: x

// when not commented (parse in both collection and model) i get:
_byCid: Object
_byId: Object
length: 6
models: Array[6]
__proto__: x

// despite it says 6, in the view you can see there are lines:
//console.log(this.collection);  <--- returns the abovee
//console.log('length: ' + this.collection.length); <-- returns 0
//console.log('models: ' + this.collection.models); <--- none

我还尝试从模型中删除所有属性防御。还是不行。返回值内容类型为:application/json(已验证),并且是有效的json。

我读过:Backbonejs集合长度总是零

但尽管console.log,显示0长度,也:

for(var i=0; i< this.collection.length; i++){
        console.log(this.collection.get(i));
}

不工作!

我还读了Did主干收集自动解析加载的数据

非常感谢

更新:我可能已经解决了这个问题:我甚至已经从模型和集合中删除了“parse”声明,并且成功了:length:6spotsview。js模型:[object object],[object object],[object object],[object object],[object object],[object object],[object object object],[object object object],[object object object],[object object object],[object object object object],[object object object object object object]。Tnx

共有1个答案

卞云瀚
2023-03-14

收藏。fetch是一个异步操作,因此当您获取集合时,将发送ajax调用,然后您的代码将继续运行,就像什么都没有发生一样。

spots.reset(); // emptied your collections

console.log(spots.fetch()); // fetch your collection (why is this inside a console.log???)

console.log('spots:'); // log some text, this will be executed right after your fetch call has been made

console.log(spots.length); // here the fetch call probably hasn't returned yet, so returns 0

console.log(spots); // same as above, so returns an empty collection

spotsview = new SpotsView({collection: spots}); // the collection might or might not get populated by the time you get to rendering so there is probably variation from program run to another

那么如何解决这个问题呢?在视图中,将呈现函数绑定到集合的重置事件(在每次成功获取或强制重置后启动)。这样,视图只有在有东西要显示时才会渲染。

// view's initialize method
initialize: function() {
  ...
  this.collection.on('reset', this.render);
  ...
} 
 类似资料:
  • 问题内容: 我是一个新用户,正在尝试此命令。 我得到这个错误 我知道这似乎是一个琐碎的问题,但我坚持下去。 问题答案: 如果编译和安装的代码是 不是 在分支(签出由默认值),但只有在该回购的分支,尝试: 然后重试编译。

  • 我有两个按钮,第一个是下一个,另一个是上一个。我想在文本视图中显示一个日期作为月份的日期。文本视图中应该看到的日期是该周的第一天。 当按下下一个按钮时,它必须显示下一周开始的第一天,而按下上一个按钮时,它必须显示上一周开始的第一天。 代码如下。 我对Android系统比较熟悉。

  • 问题内容: 我正在使用SentiWordNet做一些情绪分析,我在这里提到了如何使用SentiWordNet的帖子。但是,尽管尝试了各种输入,但我仍得到0.0分。我在这里做错什么了吗?谢谢! 这是SentiWordNet.txt的前10行 问题答案: 通常文件带有奇怪的格式。 您需要删除它的第一部分(包括注释和说明)和最后两行: 解析器不知道如何处理这些情况,如果删除这两行,就可以了。

  • 问题内容: 这应该返回一个包含图片文件名列表的JSON对象。带注释的警报显示正确的数据,但显示。 我究竟做错了什么? 问题答案: 您正在调用异步方法,该异步方法将在您的函数返回后调用其回调函数。请遵循以下示例中的注释: 您应该考虑以某种方式重构代码,以便在回调中处理JSON对象的逻辑。例:

  • 问题内容: 我正在尝试从一个简单的JSON文件填充一个集合,这是学习骨干.js的一部分。但是我无法使它工作。 进行了AJAX调用(已通过FireBug验证),但是该方法返回 。 我究竟做错了什么? 这是我的JSON: 问题答案: 是异步的,如果立即调用,则不会填充您的集合。要解决此问题,您只需将集合 重置 事件(Backbone的 同步 事件> = 1.0)绑定到视图render: 请注意bind

  • 我正在获取O并且从未进行成功的Hibernate连接测试,在学习了本教程“JasperReports with hibernate-module1”和JasperReports with hibernate-module2之后,弹出一个错误,说“Could not parse mapping document from resource com/report/mappings/department