简体   繁体   中英

Backbone.js error - Uncaught TypeError: Object [object Object] has no method 'create'

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();
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.

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