简体   繁体   中英

backbone.js model.save doesn't set the id

I've inherited a backbone js based app. I really like backbone and i'm just starting to get my head around it. From my understanding when model.save is called on a new entity it should post that to the server, the server should return the same json but with an id alloted and backbone should persist that id to the model so that further saves result in a PUT with the ID for update.

However, when I call model.save() and then try to get the model.id property, it's null.

Is this because I'm not doing it with a call back? So the property hasn't been set yet?

How would I set the success callback? calling model.save({success: function(){...}}) doesn't work?

here is the actual call:

model.save(null, {
    success: function () {
        alert('success');
    },
    error: function () {
        alert('error');
    }
});

Something feels odd about this. Setting silent: true only makes it so none of the events get fired. Everything else should happen normally. In other words, don't assume that setting slient: true is the right answer here...

I suspect you are actually throwing an exception some place (probably with validation or something like that) and somehow, setting silent: true is causing everything to flow through.

I would strongly suggest that you remove this option and check your console or run with the debugger... I suspect you have a bug lurking around there some place.

Some suggestions: Take a look at the annotated source for the model.set function. It gets called before your success callback will get called. Inside of that function, there are several things that will happen if silent is false. These include validation , individual property change triggers, and a global change trigger. I would bet money that either the validation is failing or something that is listening to the changes is throwing an exception.

我有同样的问题,原来是因为我的自定义parse失败了

i needed to set the silent: true on the save:

    model.save(null, {
        silent: true,
        success: function () {
            alert('success');
        },
        error: function () {
            alert('error');
        }
    });

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