0

Backbone.js with slim.php - When I adding a new model showing error "Uncaught TypeError: Object [object Object] has no method 'create'". Plz help me to add the new model to database.

If I use this.model.save() method it is showing 500 Internal Sever Error. Where to user create() and save() methods. I am not clear about this.

Thanks.

            // Models

    window.Users = Backbone.Model.extend({
        urlRoot:"./bb-api/users",
        defaults:{
            "name":"",
            "email":"",
            "designation":""
        }
    });

    window.UsersCollection = Backbone.Collection.extend({
        model:Users,
        url:"./bb-api/users"
    });


    // Views

    window.AddUserView = Backbone.View.extend({

        template:_.template($('#new-user-tpl').html()),

        initialize:function(){
            this.model.bind("click", this.render, this);
        },

        render:function(){
            $(this.el).html(this.template());
            return this;
        },

        events:{
            "click .add":"saveUser"
        },

        saveUser:function(){ //alert('saveUser');
            this.model.set({
                name:$("#name").val(),
                email:$("#email").val(),
                designation:$("#designation").val()
            });

            if(this.model.isNew()){
                this.model.create(this.model);
            }
        }
    });


    // Router
    var AppRouter = Backbone.Router.extend({

        routes:{
            "":"welcome",
            "add":"addUser"
        },

        welcome:function(){
            $('#content').html('Welcome to Backbone.js App');
        },          

        addUser:function(){ 
            this.addUserModel = new Users();
            this.addUserView = new AddUserView({model:this.addUserModel});
            $('#content').html(this.addUserView.render().el);
        }


    });

    var app = new AppRouter();
    Backbone.history.start();

1 Answer 1

4
if(this.model.isNew()){
    this.model.create(this.model);
}

This code is wrong, cause there is no create method in Backbone.Model. You have to call this.model.save() to send Backbone model to your server.
If the model isNew, then request from your client will be of type create. If model isn't new, then method is update.

You can (and should) read more about data synchronisation methods here: http://backbonejs.org/#Sync. Backbone.model.save delegates to your models' sync method for an actual AJAX-request sending. If model's sync isn't defined, then global Backbone.sync is used.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.