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

倖福魔咒の 提交于 2019-12-12 02:54:58

问题


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.


回答1:


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 });


来源:https://stackoverflow.com/questions/16245226/backboneparse-com-collection-fetch-returns-empty-array-using-event-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!