菜单开关

周梦康 发表于 2018-01-25 1706 次浏览 标签 : javascript

项目地址 https://github.com/rails/jquery-ujs

在线 demo

  1. 演示 jquery-ujs https://mengkang.net/demo/rails/
  2. 原理解析 - 代理表单提交 https://mengkang.net/demo/rails/2.html
  3. 原理解析 - 实现 ajax 提交 https://mengkang.net/demo/rails/3.html
  4. 扩展开发 - 行内回调 https://mengkang.net/demo/rails/4.html

项目中经常看到类似于下面这样的 a 链接的请求,而点击的时候,实际发送的是 ajax 请求,而没有发生跳转。

<a href="/comments/destroy/908/" class="js-comment-destroy"
data-remote="true" 
data-method="post" 
data-confirm="确定要删除吗?">删除</a>

演示 https://mengkang.net/demo/rails/

不是说它有多么复杂,而是我真真切切感受到了它的高效,非常舒服的抽象了模板嵌套中的一些常用的交互。避免了重复编写类似于下面这样的代码:

$("#del_btn").bind('click', function () {
  if (confirm("确定要删除?")) {
    var method = '/comments/destroy/908/';
    Ajax.sendData({
      type: 'POST',
      url: method,
      async: false,
      dataType: "json",
      data: {},
      success: function (data, status, xhr) {
        if (data.state == 'success') {
          location.href = '/articles/';
        } else {
          alert(data.msg);
        }
      },
      error: function (xhr, type, error) {
        console.log(error.toString());
      }
    });
  }
});

我们有可以在rails/jquery-ujs基础上做更多的交互扩展,文章末尾我们将把callback写在行内的方式来扩展该工具。

原理分析

A 链接实现表单的提交

虽然点击还是跳转,但是通过控制台可以看到,该请求是 post 的方式,我们自定义的 rails 插件给代理了 click 为一个 form 的 post 请求。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://static.mengkang.net/view/js/jquery-1.11.3.min.js"></script>
    <script>
        (function ($) {
            'use strict';
            var rails;
            $.rails = rails = {
                linkClickSelector: 'a[data-remote]',
                href: function (element) {
                    return element[0].href;
                },
                handleMethod: function (link) {
                    var href = rails.href(link),
                        method = link.data('method'),
                        target = link.attr('target'),
                        form = $('<form method="post" action="' + href + '"></form>'),
                        metadataInput = '<input name="_method" value="' + method + '" type="hidden" />';

                    if (target) {
                        form.attr('target', target);
                    }

                    form.hide().append(metadataInput).appendTo('body');
                    form.submit();
                },
            };

            $(document).on('click.rails', rails.linkClickSelector, function (e) {
                var link = $(this);
                rails.handleMethod(link);
                return false;
            });
        })(jQuery);
    </script>
</head>
<body>
    <a href="/comments/destroy/908/" data-remote="false" data-method="post">删除</a>
</body>
</html>

代码演示 https://mengkang.net/demo/rails/2.html

例子中

$(document).on('click.rails', 'a[data-remote]', function (e) {
  //...
});

click.railsrails是命名空间。方便解除该事件。

http://api.jquery.com/on/
One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin".

Any event names can be used for the events argument. jQuery will pass through the browser's standard JavaScript event types, calling the handler function when the browser generates events due to user actions such as click. In addition, the .trigger() method can trigger both standard browser event names and custom event names to call attached handlers. Event names should only contain alphanumerics, underscore, and colon characters.

An event name can be qualified by event namespaces that simplify removing or triggering the event. For example, click.myPlugin.simple defines both the myPlugin and simple namespaces for this particular click event. A click event handler attached via that string could be removed with .off("click.myPlugin") or .off("click.simple") without disturbing other click handlers attached to the elements. Namespaces are similar to CSS classes in that they are not hierarchical; only one name needs to match. Namespaces beginning with an underscore are reserved for jQuery's use.

实现 A 链接的 ajax 请求

在上面代码的基础上我们把data-remote参数利用上,如果data-remote设置为true则表示使用 ajax 请求。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://static.mengkang.net/view/js/jquery-1.11.3.min.js"></script>
    <script>
        (function ($) {
            'use strict';
            var rails;
            $.rails = rails = {
                linkClickSelector: ' a[data-remote]',
                href: function (element) {
                    return element[0].href;
                },
                isRemote: function(element) {
                    return element.data('remote') !== undefined && element.data('remote') !== false;
                },
                handleMethod: function (link) {
                    var href = rails.href(link),
                        method = link.data('method'),
                        target = link.attr('target'),
                        form = $('<form method="post" action="' + href + '"></form>'),
                        metadataInput = '<input name="_method" value="' + method + '" type="hidden" />';

                    if (target) {
                        form.attr('target', target);
                    }

                    form.hide().append(metadataInput).appendTo('body');
                    form.submit();
                },
                handleRemote: function(element) {
                    var options = {};

                    options.url = rails.href(element);
                    options.method = element.data('method');
                    options.data = element.data('params') || null;

                    return $.ajax(options);
                }
            };

            $(document).on('click.rails', rails.linkClickSelector, function (e) {
                var link = $(this);

                if (rails.isRemote(link)) {
                    rails.handleRemote(link);
                }else{
                    rails.handleMethod(link);
                }
                return false;
            });
        })(jQuery);
    </script>
</head>
<body>
  <a href="/comments/destroy/908/" data-remote="true" data-method="post">删除</a>
</body>
</html>

代码演示 https://mengkang.net/demo/rails/3.html

绑定到 ajax:success 做回调

$document.on('ajax:success', '.js-comment-destroy', function() {
    return $(this).closest('.media').remove();
});

这个事件是如何触发的呢?实际是在发送 ajax 里面使用trigger来触发。

options = {
    success: function(data, status, xhr) {
        element.trigger('ajax:success', [data, status, xhr]);
    },
    complete: function(xhr, status) {
        element.trigger('ajax:complete', [xhr, status]);
    },
    error: function(xhr, status, error) {
        element.trigger('ajax:error', [xhr, status, error]);
    }
}

options.url = rails.href(element);
options.method = element.data('method');
options.data = element.data('params') || null;

$ajax.(options);

扩展开发

以自定义 callback 为例,我们直接把 callback 定义在 data-done属性中。为了完全非侵入式的 JavaScript 服务端开发,才有了这个需求(反正作为一个服务端渲染的模板,不想又去专门弄前端项目,更愿意直接在模板里修改)

准备知识之 trigger + on

我们知道在 jquery 的on方法中回调函数的参数是支持无限多参数的,第一个参数event事件本身,后面都是自定义的任意内容

handler Type: Function( Event eventObject [, Anything extraParameter ] [, ... ] )
http://api.jquery.com/on/#on-events-selector-data-handler

配合trigger来使用,两个参数演示

$( "div" ).on( "click", function( event, person ) {
  alert( "Hello, " + person.name );
});
$( "div" ).trigger( "click", { name: "Jim" } );

trigger传递数组

$( "div" ).on( "click", function( event, salutation, name ) {
  alert( salutation + ", " + name );
});
$( "div" ).trigger( "click", [ "Goodbye", "Jim" ] );

到这里我们就可以看到 jquery-ujs 在发送 ajax 的 options 里面设置了

options = {
    success: function(data, status, xhr) {
        element.trigger('ajax:success', [data, status, xhr]);
    },
    //...
}
//...
$ajax.(options);

那我们绑定到data-done上就是

$(document).on('ajax:success', '[data-done]', function(event, data, status, xhr) {
  //...
});

准备知识之 new Function() + call

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

var obj = {
  person: 'Douglas Crockford'
};

function funA() {
  console.log(this.person);
}

funA.call(obj);

function funB(arg1,arg2) {
  console.log(this.person,arg1,arg2);
}

funB.call(obj,1,2);

// new Function (arg1, arg2, ... argN, functionBody)
new Function('arg1','arg2','console.log(this.person,arg1,arg2)').call(obj,3,4);

实现 data-done 回调

代码演示:https://mengkang.net/demo/rails/4.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://static.mengkang.net/view/js/jquery-1.11.3.min.js"></script>
    <script>
        (function ($) {
            'use strict';
            var rails;
            $.rails = rails = {
                linkClickSelector: ' a[data-remote]',
                href: function (element) {
                    return element[0].href;
                },
                handleRemote: function (element) {
                    var options = {
                        success: function (data, status, xhr) {
                            element.trigger('ajax:success', [data, status, xhr]);
                        }
                    };

                    options.url = rails.href(element);
                    options.method = element.data('method');
                    options.data = element.data('params') || null;
                    options.dataType = 'json';

                    return $.ajax(options);
                }
            };

            $(document).on('click.rails', rails.linkClickSelector, function (e) {
                rails.handleRemote($(this));
                return false;
            });

            $(document).on('ajax:success', '[data-done]', function (event, data, status, xhr) {
                console.log(data, "\n", status, "\n", xhr);

                var done = $(this).data('done');
                if (done) {
                    (new Function('data', done)).call(this, data);
                }
            });
        })(jQuery);
    </script>
</head>
<body>
<div class="media">
    <a href="del.php"
       data-remote="true"
       data-method="post"
       data-done="$(this).closest('.media').remove()"
    >删除 - 删掉整个 div</a>

    <a href="del.php"
       data-remote="true"
       data-method="post"
       data-done="alert(data.error_code)"
    >输出接口里返回的error_code</a>
</div>

</body>
</html>

嗨,老铁,欢迎来到我的博客!

如果觉得我的内容还不错的话,可以关注下我在 segmentfault.com 上的直播。我主要从事 PHP 和 Java 方面的开发,《深入 PHP 内核》作者之一。

[视频直播] PHP 进阶之路 - 亿级 pv 网站架构的技术细节与套路 直播中我将毫无保留的分享我这六年的全部工作经验和踩坑的故事,以及会穿插着一些面试中的 考点难点加分点

评论列表