在backbone和parse.com中建立模型和集合之间的连接

时间:2013-05-03 11:06:10

标签: backbone.js parse-platform

我正在尝试使用parse.com连接模型和集合,但我很困惑。我想通过使用backbone和javascript api parse.com的集合来获取,但比较这个错误:POST https://api.parse.com/1/classes 404(Not Found)。

型号:

    var Person = Backbone.Model.extend({


  defaults:{




      },


  initialize:function(){
          console.log("inperson");
          this.validate();
          this.send();
      },

  validate:function(){
          console.log("validate");
      },

      send:function(){
           var user = new Parse.User();
           user.set("username", this.get("username"));
           user.set("password", this.get("password"));
           user.set("email", this.get("email"));



           user.signUp(null, {
           success: function(user) {
// Hooray! Let them use the app now.
            },
           error: function(user, error) {
// Show the error message somewhere and let the user try again.
           alert("Error: " + error.code + " " + error.message);
           }
 });


      }






});




  return Person;
  });

收集:

  var Usercollection = Parse.Collection.extend({

 model:Person,



  initialize:function(){




 }

  });






return Usercollection;



});

最后是调用colletion和fetch的视图:

var HomeView = Backbone.View.extend({

template: Handlebars.compile(template),

 events: {


  },

  initialize: function() {

      console.log("inhomeview");

      var amici = new Usercollection();
    amici.fetch({
  success: function(collection) {
   amici.each(function(object) {
  console.warn(object);
});
},
error: function(amici, error) {
// The collection could not be retrieved.
}
 }); 



  },

   render: function() {


    }



 });

 return HomeView;

});

1 个答案:

答案 0 :(得分:0)

Cant you just swap the backbone collection and model to Parse's ones? (You only used the Parse type of the collection, not the model!) Try switch that Backbone model to a Parse.Object .

Step by step below:

First of all Lets create a new app on Parse.com, mine is called FunkyAppartments. Insert the script tag for loading Parse javascript lib into index.html or whathever:

<script src="http://www.parsecdn.com/js/parse-1.5.0.min.js"></script>

Switch the backbone model and collection to use parse types instead (and rename the fetch method if you have extended backbones, since we do not want to overide the one of parse):

  //var Appartment = Backbone.Model.extend(); Backbone wo. Parse.com
  var Appartment = Parse.Object.extend("Appartment");

  //var Appartments = Backbone.Collection.extend({ Backbone wo. Parse.com
  var Appartments = Parse.Collection.extend({
    model: Appartment,
    loadAppartments: function(callback){
      debugger;
      this.query = new Parse.Query(Appartment);
      this.fetch();
    }

  });

I added a debugger tag in the load appartments so that developer tools breaks in the middle of the controller, here I have access to the Appartment private type of the controller, hence i can store some data on the parse server and verify by pasting the below in the developer tools console.

var testAppartment = new Appartment();
testAppartment.save({name: "foobars"}).then(function(object) {
  alert("yay! it worked");
});

Yei, the data shows up in the parse.com UI for the app we just added there. And more importantly it shows up in our frontend. That was easy!

UPDATE: PROBLEMS W BACKBONE 1.2.1, MARIONETTE 2.4.2, UNDERSCORE 1.8.3

I noticed that I actually had been using old versions of marionette, backbone and underscore.js. An initial update appeared to break the application.

After some research i found that it was the parse part that did not return objects that would successfully render. Hence I changed the collection type back to an extension of: Backbone.collection instead of Parse.collection.

I also had to override the query method, since the objects would not save on the correct id, updating an object resulted in a new object being added instead of an old one being updated.

var Apartment = Parse.Object.extend('Appartment');

var Apartments = Backbone.Collection.extend({
  model: Apartment,
  query: new Parse.Query(Apartment),
  initialize: function(){
    MyApp.vent.on('search:param', function(param){self.search(param); });
    var self = this;
    this.query.find({
        success: function(results){
            self.reset();
            results.forEach(function(result){
              result.attributes.id__ = result.id
              var ap = new Apartment(result.attributes);
              self.add(ap);
            });
          }
      });
  }
});

I added an attribute: id__ to hold the parse id (naming it just id did not work since it backbone interfered with it, making it disappear). Finally in saving the model to parse i utilized id__ as id in the save call:

  var ApartmentEditView = Backbone.Marionette.ItemView.extend({
    template: "#apartment-edit-template",
    className: "apartmentDetail",
    events: {
      "click .store": "storeEdit",
      "click .close": "closeEdit"
    },
    storeEdit: function(){
      var priceNum = Number($('#price_field').val().replace(/\s/g, ''));

      this.model.set({
        id: this.model.attributes.id__,
        name:$('#name_field').val(),
        price:priceNum,
        description:$('#desc_field').val(),
        url:$('#url_field').val()
      });
      this.model.save();
      this.closeEdit();
    },
    closeEdit: function(){
      var detailView = new ApartmentDetailView({model: this.model});
      MyApp.Subletting.layout.details.show(detailView);
    }
  });

Now the object is updated correctly in the database.