简体   繁体   English

编辑Backbone Ajax成功方法以添加自定义错误处理

[英]Edit Backbone Ajax Success Method to Add in Custom Error Handling

I have my own custom error code inside of a backbone ajax success method in case the server returns an error. 在服务器返回错误的情况下,我在主干ajax成功方法中有自己的自定义错误代码。 The problem is that this code is repeated throughout my app and I wanted to edit the success function in one place so I don't have to constantly repeat this error handler in every ajax success. 问题在于此代码在我的整个应用程序中都重复了,我想在一个地方编辑成功函数,因此我不必在每次ajax成功中都不断重复此错误处理程序。 I want to edit the success function to include this error check wrapper. 我想编辑成功函数以包括此错误检查包装器。 Do you know how to do that? 你知道怎么做吗?

Here is an example of my success method in one of my views: 这是我的一种看法,是我成功方法的一个例子:

"success" : function success(model, data)
             {
              if(data['error'] !== undefined && data['error'].length === 0)
               {
                message('error', 'Whoops! System Error. Please refresh your page.');
               }
              else if(data['error'] !== undefined)
               {
                message('error', data['error']);
               }
              else
               {
                //add templates and do stuff here
               }
             },

Ideally I'd like to set that in a config somewhere and then I'd just be able to use: 理想情况下,我想在某个地方的配置中设置它,然后就可以使用:

"success" : function success(model, data)
             {
              // add templates and do stuff here
             }

Is this possible? 这可能吗? I tried using ajaxSetup but that didn't seem to work for me. 我尝试使用ajaxSetup,但这似乎对我不起作用。

UPDATED CODE STILL NOT WORKING: 更新的代码仍然无法正常工作:

That does get me a little further along but the error handler isn't functioning as a wrapper. 这确实使我走得更远,但是错误处理程序无法充当包装器。 The data is not being passed into my ajax calls. 数据没有传递到我的ajax调用中。 In fact, my success methods on my ajax calls aren't running at all anymore. 实际上,我对ajax调用的成功方法根本不再运行。 I tried console.log("some text") in my ajax calls but nothing is being output. 我在ajax调用中尝试了console.log(“ some text”),但没有输出任何内容。 Do you know what is wrong with this? 你知道这是怎么回事吗?

// Save the original Sync method
defaultSync = Backbone.sync;

//Over ride Backbone async
Backbone.sync = function(method, 
                         model, 
                         options) 
                 {
                  success = options.success

                  options.success = function(data) 
                                     {
                                      if(data['error'] !== undefined && data['error'].length === 0)
                                       {
                                        message('error', 'Whoops! System Error. Please refresh your page.');
                                       }
                                      else if(data['error'] !== undefined)
                                       {
                                        message('error', data['error']);
                                       }
                                      else
                                       {
                                        success(model, 
                                                data);
                                       }
                                     }

                  return defaultSync(method, 
                                     model, 
                                     options)
                 }

There are two ways to solve this: 有两种解决方法:

  • Inheriting Backbone Model 继承骨干模型

You could create your own custom model which inherits from Backbone Model. 您可以创建自己的自定义模型,该模型继承自Backbone Model。 In it you could override the save method. 您可以在其中覆盖save方法。 Read Backbone docs on how to extend their model 阅读Backbone文档,了解如何扩展其模型

In your custom save method, you will call the save method of super, check the responseText, if it's success then you'll call the success callback. 在自定义保存方法中,将调用super的save方法,检查responseText,如果成功,则将调用成功回调。 (please do read backbone docs on how to call a method of your parent model in Javascript) (请阅读有关如何在Javascript中调用父模型的方法的骨干文档)

  • Override Backbone.Sync 覆盖Backbone.Sync

Backbone has a Sync module which basically by default makes all ajax requests, parses the response and then calls the success/error callbacks you specified when calling save on your model. Backbone具有一个Sync模块,该模块基本上默认情况下发出所有ajax请求,解析响应,然后调用在模型上调用save时指定的成功/错误回调。 It's pretty simple. 很简单 Take a look at this doc . 看看这个文档 Again you could override this, do exactly what Backbone is doing by default but only call the success/error callbacks based on responseText you received. 同样,您可以覆盖此设置,完全按照Backbone的默认设置进行操作,但仅根据收到的responseText调用成功/错误回调。

UPDATE: Sample Code (warning code not tested) 更新:示例代码(警告代码未经测试)

//Over ride Backbone async

defaultSync = Backbone.Sync // Save the original Sync method. We'll be needing that.

Backbone.Sync = function(method, model, options) {
   success = options.success
   error = options.error

   options.success = function(model, data, options) {
      if (/% all your custom checks are true */) {
           success (model, data, options);
      }
      else {
         error(model,data,options);
     }
    }

   return defaultSync(method, model, options);

}

Please make sure with this strategy the Sync method will be overriden for ALL your Backbone sync. 请确保使用此策略,所有Backbone同步都将覆盖Sync方法。 If you don't want that then use Model#save override. 如果您不希望这样做,请使用Model#save覆盖。

Take a look at this code where I am overriding Backbone.Sync to make it work with Parse.com API. 看一下这段代码 ,其中我重写了Backbone.Sync以使其与Parse.com API一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM