2015年8月6日 星期四

JQuery-ujs 的運作模式 - Unobtrusive scripting adapter for jQuery


在經歷這麼多專案之後,時常會看到以下的設定,卻不知道是用來做什麼的:

Gemfile
gem 'jquery-rails'

application.js
//= require jquery
//= require jquery_ujs


來介紹一下貝殼幾乎每個專案都會使用到的: JQuery-ujs



舉例來說,會有以下幾個常用的狀況:

link_to "click me!", posts_path, data: { confirm: "Are you sure?" }
button_to "submit", posts_path, data: { diable_with: "loading..." } 
還有上篇 Remotipart - Upload File via AJAX 提過的:
simple_form_for @post, html: { multipart: true }, remote: true do |form|
...
end

這些設定會經由 Rails 內建的 ActionView::Helpers 產生 相對應的 HTML:
<a ... data-remote="true">
<button ... data-confirm="Are you sure?">
<form ... data-disable-with="loading...">


而後引入 jquery_ujs 這支 Javascript 時,便會依照這些 data-xxx 屬性作出相對應的設定。
以 data-remote="true" 來說:

  1. 覆寫所有 click event / submit action,讓它們經由 AJAX 發送請求
  2. 綁定 4 個 AJAX callback function,在需要時可以覆寫這些 function(ajax:beforeSend, ajax:success, ajax:complete, ajax:error)
沒想到一行簡單的 code ,Rails 在背後做了這麼多事!
如果想瞭解更詳細的內容,可以參考 JQuery-ujs/rails.js


沒有留言:

張貼留言