简体   繁体   中英

Backbone.js: Save's success function simply does not work

I'm trying to get the most basic thing running in Backbone.js but somehow fail. The code I've produced for saving a model into the server. 模型保存到服务器而生成的代码。

urlToAdd.set({url: urlBody.value, tags:tagsToAdd});
                urlToAdd.save({
                    success:function(){
                        console.log('it works');
                    }
                });

It sends the data to my php page however I can not get event to work. 将数据发送到我的php页面但是我无法获得事件。 Where am I doing wrong? I've carefully observed and couldn't find anything.

Here is my model definition: (Unfortunately since I am backbone noob I've applied this by checking a tutorial and I have no idea if the codes in function are necessary 函数中的代码是否是必要的

var URLWithTags=Backbone.Model.extend({
            initialize:function(){
                console.log('URL object has been initialized');
            },
            defaults:{
                url:'not defined',
                tags:[]
            },
            validate:function(attributes){
            //console.log(attributes.tags[0].length);
                /*if(attributes.tags[0].length<1)
                    return "You should create at least one tag";*/
            },
            urlRoot:'/URLTags/manage.php',
            url:function(){
                var base = this.urlRoot || (this.collection && this.collection.url) || "/";
                console.log("Base has been produced");
                if(this.isNew())
                    return base;

                return base+"?id="+encodeURIComponent(this.id);
            },
        });

Save should be the second argument in an object when you call the save function. please people read the doc , or the source it is well commented ,short and easy to read.

urlToAdd.save(null,{success:function(){console.log('it works')}});

according to the doc :

savemodel.save([attributes], [options]) ;

so :

urlToAdd.save({},{success:successCallback , error:errorCallback}); 

EDIT

Exemple :

    var Car,yukon,$target ;
    Object.prototype.toString = function(){
        return JSON.stringify(this);
    };

    Car = Backbone.Model.extend({
        url:"/echo/json"
    });
    yukon= new Car({"color":"red","brand":"GM"});
    $target = $("#target");

    $target.append("describe yukon :",yukon.toString(),"<br/>");

    yukon.save({},
{
success:function(o){$target.append("save success <br/>",o.toString())},
error:function(e){$target.append("error",e)}
}
); 

where $target is a jquery object representing a div with the id of target.

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