资讯专栏INFORMATION COLUMN

使用 rails/jquery-ujs 来编写非侵入式的 js 模板代码

Me_Kun / 1203人阅读

摘要:确定要删除吗删除演示不是说它有多么复杂,而是我真真切切感受到了它的高效,非常舒服的抽象了模板嵌套中的一些常用的交互。删除代码演示例子中中是命名空间。删除代码演示绑定到做回调这个事件是如何触发的呢实际是在发送里面使用来触发。

sf 上前端大牛太多,本人前端菜鸟,总结归纳,觉得内容不错就总结分享之。

惯例安利一波我的后端 php 直播课。
很多工程师在工作1~3年的时候最容易遇到瓶颈,不知道自己应该学习什么,面试总是吃闭门羹。那么 PHP 后面应该怎么学呢?《PHP 进阶之路》

原文地址 https://mengkang.net/1145.html
项目地址 https://github.com/rails/jque...
在线 demo

演示 jquery-ujs https://mengkang.net/demo/rails/

原理解析 - 代理表单提交 https://mengkang.net/demo/rai...

原理解析 - 实现 ajax 提交 https://mengkang.net/demo/rai...

扩展开发 - 行内回调 https://mengkang.net/demo/rai...

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

删除
演示 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 请求。




    
    Title
    
    


    删除

代码演示 https://mengkang.net/demo/rai...

例子中

$(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 请求。




    
    Title
    
    


  删除

代码演示 https://mengkang.net/demo/rai...
绑定到 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-... 中

配合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...
https://developer.mozilla.org...
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/rai...



    
    Title
    
    





文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/92815.html

相关文章

  • Spring体系常用项目一览

    摘要:的面向的异常遵从通用的异常层次结构。比如以前常用的框架,现在常用的框架包含许多项目,下面挑一些最常用的出来总结一下。状态是流程中事件发生的地点,在流程中通过转移的方式从一个状态到另一个状态,流程的当前状况称为流程数据。 如今做Java尤其是web几乎是避免不了和Spring打交道了,但是Spring是这样的大而全,新鲜名词不断产生,学起来给人一种凌乱的感觉,我就在这里总结一下,理顺头绪...

    OnlyLing 评论0 收藏0
  • 类型系统-前端进化的里程碑

    摘要:这些优势,其实都是类型系统所带来的强类型语言所具有的开发优势,无论是在开发体验还是后期项目维护上,都要优于目前的。 大半夜的JavaScript Weekly发来贺电:TypeScript 2.0 Final Released! 没错,继Angular2发布之后,TypeScript今天也发布了2.0版本,这不禁让我浮想一番。如果要说TS和JS最明显的差别,我想一定是Type Syst...

    wangzy2019 评论0 收藏0
  • Spring入门看这一篇就够了

    摘要:甲乙交易活动不需要双方见面,避免了双方的互不信任造成交易失败的问题。这就是的核心思想。统一配置,便于修改。带参数的构造函数创建对象首先,就要提供带参数的构造函数接下来,关键是怎么配置文件了。 前言 前面已经学习了Struts2和Hibernate框架了。接下来学习的是Spring框架...本博文主要是引入Spring框架... Spring介绍 Spring诞生: 创建Spring的...

    superw 评论0 收藏0
  • Java培训学习之Java开源软件的汇总

    摘要:开源软件的汇总开源插件是一个类似于的插件,它可以帮助你在不退出的环境下浏览本地文件系统。事件模型支持基于的事件提交。开源容器是一个非侵入式的对象反转控制容器容器。开源插件提供一个可针对文件语法进行着色的编辑器。 Java开源软件的汇总:EcSplorer 【Java开源 Eclipse插件】EcSplorer(Eclips...

    qiangdada 评论0 收藏0
  • 【译】《精通使用AngularJS开发Web App》(二) --- 框架概览,双向数据绑定,MVC

    摘要:本书的这一部分将为随后的章节打下基础,会涵盖模板,模块化,和依赖注入。本书的小例子中我们会使用未经压缩的,开发友好的版本,在的上。作用域也可以针对特定的视图来扩展数据和特定的功能。 上一篇:【译】《精通使用AngularJS开发Web App》(一) 下一篇:【译】《精通使用AngularJS开发Web App》(三) 原版书名:Mastering Web Application D...

    geekidentity 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<