0

最後まで読んでください(最後に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;
});

app.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 length を示しています。

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

うまくいきません!

また、バックボーンコレクションはロードされたデータを自動的に解析しましたかを読み ました

どうもありがとう

更新:私はおそらくそれを解決しました:私はモデルとコレクションから「パース」宣言さえ削除しました. ],[object Object],[object Object],[object Object] いずれにせよ、適切な使用法を知りたいのですが、私が正しいことをした場合、およびPARSEを両方の状況で正しい方法で(コレクションとモデルに関して)どのように使用するかを知りたいです。両方に戻りますか (!)。TNX

4

1 に答える 1

0

Collection.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

では、これを修正する方法は?ビューで、render 関数をコレクションのリセット イベントにバインドします (フェッチまたは強制リセットが成功するたびに起動されます)。このようにして、表示するものがある場合にのみビューがレンダリングされます。

// view's initialize method
initialize: function() {
  ...
  this.collection.on('reset', this.render);
  ...
} 
于 2012-07-23T10:14:41.123 に答える