Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

backbone.js - Backbone+Parse.com Collection.fetch() returns empty array using event callback

i'm starting using parse.com to develop a web app but i'm stuck on a simple problem. I defined a model (or object in Parse SDK) as:

Book.Model = Parse.Object.extend("book", {
    // Default attributes for the book.
    defaults: {
      title: "placeholder...",
    },

    // Ensure that each book created has `title`.
    initialize: function() {
      if (!this.get("title")) {
        this.set({"title": this.defaults.title});
      }
    },

  });

and a collection:

Book.List = Parse.Collection.extend({

    // Reference to this collection's model.
    model: Book.Model,

    initialize: function() {
    },

  });

Then, if i try something like

   var books = new Book.List();
   books.fetch({
        success: function(collection) {
            console.warn(collection);
        },
        error: function(collection, error) {
           // The collection could not be retrieved.
        }
    });

Everything goes fine. Log:

child {length: 5, models: Array[5], _byId: Object, _byCid: Object, model: function…}
_byCid: Object
_byId: Object
length: 5
models: Array[5]
__proto__: EmptyConstructor

BUT if i try to use event callback instead of success method i get an empty array. Code:

books.on('reset', this.log());
books.fetch();

    log: function() {
      console.log(books);
    }

and log:

child {length: 0, models: Array[0], _byId: Object, _byCid: Object, model: function…}
_byCid: Object
_byId: Object
length: 5
models: Array[5]
__proto__: EmptyConstructor

which is quite strange (because i think that each solution wait for the collection to be populated from the server). Does anybody know why is this happening?

I'm actually using Backbone Boilerplate and Parse.com js SDK.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The Collection#fetch behavior has changed, it used to reset the collection by default but as of 1.0.0 it merges the new models using set:

When the model data returns from the server, it uses set to (intelligently) merge the fetched models, unless you pass {reset: true}, [...]

and set doesn't trigger "reset" events, it triggers other events:

All of the appropriate "add", "remove", and "change" events are fired as this happens.

If you want your fetch to reset the collection then you have to say so:

books.fetch({ reset: true });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...