Backbone toJSON
Asked Answered
Q

1

5

I am either massively tired or really confused... But I'm not sure... I have a parse.com javascript setup (it's exactly like backbone.js just with the parse instead of backbone). And I have a model, and a collection, and it all works. But the darn toJSON(); does not work, it just returns a [] in console.log... However if I run the same function in Chromes console it works and returns the correct values.

Any help!?

All this lovely code is wrapped in a document ready (and it had some other code which is not relavent and yes I have Parse.initialize()'d it.

  var Schedule = Parse.Object.extend({
    className: "schedule"
  });

  var ScheduleList = Parse.Collection.extend({
    model: Schedule
  });

   schedule = new ScheduleList();
      schedulejs3 = schedule.toJSON();
      schedule.query = new Parse.Query(Schedule);
      schedule.query.ascending("date");
      schedule.query.limit('500');
      schedulejs2 = schedule.toJSON();
      schedule.fetch();

      schedulejs = schedule.toJSON();
      console.log(schedulejs,schedulejs2,schedulejs3); <-- All three return []

  var ScheduleView = Parse.View.extend({
    el: $("#schedule-holder"),
    initialize: function() {
      this.schedule = new ScheduleList();
      this.schedule.query = new Parse.Query(Schedule);
      this.schedule.query.ascending("date");
      this.schedule.query.limit('500');

      this.schedule.fetch();

      this.schedule.js = this.schedule.toJSON();

      this.render;
    },

    render: function() {
      var template = Handlebars.compile($("#schedule-item").html());
      $(this.el).html(template({shows: this.schedule.toJSON()}));
      return this;
    }
  });

  var App = new ScheduleView().render();

But if I open console in Chrome and run schedule.toJSON(); I get the correct values... As you can see I've kind of butchered my backbone.js setup trying to figure this out (incase you are wondering why everything is all over the place). And a little note, I'm using Zepto.js not jQuery.

Thanks!

Quintan answered 29/8, 2012 at 13:9 Comment(0)
W
19

Probably at the time you execute schedule.toJSON() it is still empty.

Remember that Collection.fetch() is an asynchronous method.

Try to modify this line:

schedule.fetch();

By this:

schedule.fetch({ success: function() { console.log( "what about now?", schedule.toJSON() ) } };

(Probably you will come with a context issue try to make schedule variable to be accesible into the success handler)

Wahlstrom answered 29/8, 2012 at 13:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.