ページ

2013年1月30日水曜日

coffeescript+jQueryでDOM操作

やりたいこと

coffeescriptで生成したjavascriptでDOM操作をしたい

今回学んだこと

coffeescriptの1行目に
$ ->
と記述することで、それ以下の命令がdocument読み込み完了時に実行される。
jQueryの下記の記述と同等。
$(function() {
  //何らかの処理
});

ディレクトリ構造

shusuke@shusuke-VirtualBox:~/practice/coffee$ pwd
/home/shusuke/practice/coffee
shusuke@shusuke-VirtualBox:~/practice/coffee$ tree
.
├── bin
│   └── hello.js <-coffeescriptをコンパイルしてできたJSファイル
├── lib
│   └── jquery-1.9.0.min.js
├── src
│   └── hello.coffee <-coffeescriptのソースファイル
└── view.html <-練習用のHTML

view.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja">
<head>
<meta http-equiv="Content-Language" content="ja" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <script type="text/javascript" src="./lib/jquery-1.9.0.min.js"></script>
  <!-- javascriptを読み込む -->
  <script type="text/javascript" src="./bin/hello.js"></script>
</head>
<body>
  <div id="apple">りんご</div>
  <div id="banana">バナナ</div>
  <div id="hoge">HOGE</div>
</body>
</html>

src/hello.coffee

$ ->
  console.log "LOG TEST"
  hoge = $('#hoge')
  msg = if hoge is null then "hoge is null" else "hoge is not null"
  console.log msg
  console.log hoge.html()

bin/hello.js

// Generated by CoffeeScript 1.4.0
(function() {

  $(function() {
    var hoge, msg;
    console.log("LOG TEST");
    hoge = $('#hoge');
    msg = hoge === null ? "hoge is null" : "hoge is not null";
    console.log(msg);
    return console.log(hoge.html());
  });

}).call(this);

実行結果(HTML表示時のjavascriptコンソール)

[23:24:31.514] LOG TEST
[23:24:31.514] hoge is not null
[23:24:31.515] HOGE