如何检查服务器上是否存在骨干模型

sil*_*min 2 model backbone.js

如果我做

var model = new Model({ id : 'someNewId'});
model.fecth();
Run Code Online (Sandbox Code Playgroud)

然后我得到一个带有默认值的模型作为模型,因为服务器上不存在'someNewId'的想法.

什么是确保服务器上存在模型的最佳方法?

jev*_*lio 6

这实际上取决于您的服务器配置.通常,RESTful服务将返回HTTP错误代码404以指示未找到资源.

model.fetch({
    success: function(model, response, options) {
        //model exists and is now populated
    },

    error: function(model, xhr, options) {
        if(xhr.status === 404) {
            //model was not found
        } 
        else {
            //some other error
        }
    }
}
Run Code Online (Sandbox Code Playgroud)