简体   繁体   中英

Backbone.js model.save returns TypeError?

I'm trying to implement backbone.js model which looks like this in Django:

class Booking(models.Model):
    date        = models.DateField('date booked')
    time        = models.TimeField('time booked')
    duration    = models.PositiveSmallIntegerField('duration booked') #x * 15
    user        = models.ForeignKey(User, related_name='bookings')
    room        = models.ForeignKey(Room, related_name='bookings')
    description = models.TextField()

It's served through a RESTful interface via TastyPie: /api/booking. My backbone model is set up like this as per instructions here :

window.Booking = Backbone.Model.extend({
url     :   function(){
                return this.get('resource_uri') || this.collection.url;
            },
urlRoot :   "/api/booking",
defaults:   {
                user    :   "/api/user/5" //defaults to nobodys
                }
});
window.Bookings = Backbone.Collection.extend({
url         :   BOOKING_API,
parse       :   function(data){
                return data.objects;
            }
});

Now trying to test it out in console like this:

var booking = new Booking({date : "2011-08-17", time: "12:45", duration: 30, room: "/api/room/1", description: "quickbook"});
booking.save();

The above code returns a TypeError. I don't see what I'm doing wrong.

You are not defining a resource_uri or putting your booking in a collection. The TypeError you are seeing is from this.collection.url. You would see the same error doing booking.collection.url. Something like the following should do the trick.

var bookings = new Bookings;
bookings.add(booking);
booking.save();

Because when you call save() method there is no resource_uri and no this.collection in model. So your url returns undefined

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM