Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby on Rails | underscore.jsでJavaScriptの便利なユーティリティを利用

概要

underscore.jsでJavaScriptの便利なユーティリティを利用

詳細

コレクション向けのAPIなど便利なユーティリティを利用できるunderscore.jsを
Railsに組み込みます。
underscore.jsの詳細については下記参照。
http://documentcloud.github.io/underscore/

設定手順

application.jsに下記を追記

 //= require underscore

vender/assets/javascriptsにunderscore.jsをコピー

サンプル

Coffee Script+jQueryと組み合わせてフォームのクリア機能を実装。
eachでRubyのブロック風にフォームの要素を処理しています。

class @Page
  @clear_form: (f) ->
    _.each($(f).find(":input"), (elm) ->
      switch elm.type
        when 'password','select-multiple', 'select-one', 'text', 'textarea'
          $(elm).val("")
        when 'checkbox', 'radio'
          elm.checked = false
        when 'hidden'
        else
    )