Search code examples
backbone.jsmarionette

Backbone correct way to extend Backbone.Model


I am trying to use RESTful api to signup a user.

Here is my model code:

var User = Backbone.Model.extend({
    idAttribute: '_id',
    host: 'http://localhost:3000',
    url: '/api/user'
});

This is the code in my view for handling signup button click:

signupClick: function (e) {
    e.preventDefault();
    var email = $('#input-email').val();
    var pwd1 = $('#input-pwd').val();
    var pwd2 = $('#input-pwd2').val();

    if(pwd1 !== pwd2) {
        return alert('password does not equal');
    }

    var user = new UserModel({email: email, password: pwd1});
    user.sync();

}

The API is on localhost: POST /api/user Body: {email:'[email protected]', password:'123456'}

But I got the following error msg in browser console:

Uncaught Error: A "url" property or function must be specified

What did I do wrong in this model? Thanks!


Solution

  • By default, models generate a url by deferring to their containing collection's "url()" function. If you have a model which is not managed by a collection, you should specify the model's "urlRoot" property.

    So, in your example, change your model to this and you should get what you're after:

    var User = Backbone.Model.extend({
        idAttribute: '_id',
        host: 'http://localhost:3000',
        urlRoot: '/api/user'
    });
    

    [ relevant documentation is here: http://backbonejs.org/#Model-url ]