简体   繁体   English

jQuery为与AJAX一起使用的插件实现成功和错误回调

[英]Jquery implementing a success and error callback for my plugin that works with AJAX

I have written a small Jquery plugin that makes it easy for me to implement Facebook like "likes" on any item in my application. 我编写了一个小的Jquery插件,使我可以轻松地在应用程序中的任何项目上实现像“喜欢”这样的Facebook。 My only issue now is that I struggle to implement the success / error callback of my plugin. 我现在唯一的问题是我很难实现插件的成功/错误回调。

$('.user-like').like({
    success: function(data, textStatus, jqXHR) {
        $(this).text('Liked');
    }
});

My issue with the above code is this line: 我上面的代码的问题是这一行:

$(this).text('Liked');

I'm aware of what why the issue happens, I just can't find a good way to make it work like I want it. 我知道问题发生的原因,只是找不到一种使它如我所愿地工作的好方法。 Let me explain how the script works and what my Goal is: 让我解释一下脚本的工作原理以及我的目标是:

As you can see I'm passing the call along to the likeApi() function that executes an AJAX call. 如您所见,我将调用传递给了执行AJAX调用的likeApi()函数。 Further you see that I merge my Options with the defaults and that you can override the success and error callback of the AJAX object. 此外,您还将看到我的Options与默认值合并,并且您可以覆盖AJAX对象的成功和错误回调。

The issue is now that this in the above code is the scope of the AJAX call and not my original method. 问题是,现在this在上面的代码是AJAX调用的范围,而不是我原来的方法。 I want to allow the user to define his own success / error callback that depends on the result of the API call and allows me to do something based on the state if it was a success or failure so that I can change the like text for example. 我想允许用户定义自己的成功/错误回调,该回调取决于API调用的结果,并允许我根据状态执行成功还是失败的操作,以便例如可以更改类似的文本。 How can I do this? 我怎样才能做到这一点?

(function ($) {

    $.likeApi = function (action, options) {
        if (action != 'like' && action != 'unlike') {
            return false;
        }
        var options = jQuery.extend({}, jQuery.likeApi.defaults, options);
        $.ajax({
            type: "POST",
            url: options.baseUrl + action + '.json',
            data: {
                data: {
                    Like: {
                        foreign_key: options.id,
                        model: options.model
                    }
                }
            },
            success: options.success,
            error: options.error,
            dataType: 'json'
        });
    };

    $.fn.like = function (options) {
        var scopedOptions = options;
        this.on('click', function(event) {
            event.preventDefault();
            $.likeApi('like', $.extend({}, scopedOptions,{
                'id': $(event.target).data('like-fk'),
                'model': $(event.target).data('like-model')
            }));
        });
        return this;
    };

    $.fn.unlike = function (options) {
        var scopedOptions = options;
        this.on('click', function(event) {
            event.preventDefault();
            var result = $.likeApi('unlike', $.extend({}, scopedOptions,{
                'id': $(event.target).data('like-fk'),
                'model': $(event.target).data('like-model')
            }));
            alert(result);
        });
        return this;
    };

    $.likeApi.defaults = {
        baseUrl: '/likes/likes/',
        action: null,
        model: null,
        id: null,
        error: function(jqXHR, textStatus, errorThrown) {
            alert(textStatus);
        },
        success: function(data, textStatus, jqXHR) {
            alert(textStatus);
        }
    };

}(jQuery));

Two options: you can maintain context by adding a variable that references the original this , or you can use jquery.proxy() 两个选择:您可以通过添加引用原始this的变量来维护上下文,或者可以使用jquery.proxy()

Option 1 : Maintain the context by adding a variable that references the original this like so: 选项1:通过添加引用原始变量保持的上下文this像这样:

(function ($) {
    $.likeApi = function (action, options) {
        var self = this;

Then you just call self whenever you are out of context. 然后,只要不在上下文中,您就可以称呼self

If you want to keep self available externally, you can inject it using jquery extend. 如果要在外部保持self可用,可以使用jqueryextend inject它。 http://api.jquery.com/jquery.extend/ http://api.jquery.com/jquery.extend/

options.success = $.extend(options.sucesss, {el: self});

inside your ajax call 在你的ajax电话内

$('.user-like').like({
    success: function(data, textStatus, jqXHR) {
        $(data.el).text('Liked');
    }
});

Option 2 : Alternatively, you can use jQuery.proxy() http://api.jquery.com/jquery.proxy/ 选项2 :或者,您可以使用jQuery.proxy() http://api.jquery.com/jquery.proxy/

proxy can change the this context for you... 代理可以为您更改this上下文...

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

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