Archive for the ‘jQuery’ Category

[haXe][js] haXe で jQuery を使う方法

Category:{ haXe, javascript, jQuery }  Tag:{, , } Comments:{ 1 Comment }
Posted:{ 2012.01.09 10:02:48 }

「js の prototype なじめないんです!」
extendsとかしたいんです!」
静的型付けじゃないと、安心してねれないんです!(´・ω・`)」

って病気の人いませんか?(私です)

「じゃ haXe で js やってみればいいんじゃね?」

でもライブラリ (jQueryとか) どうやって使うんだろ?」

。。ということで、haXe で jQuery を使う手順メモです。

※そもそもhaXeって何?って方はこちら
※haXeの開発環境 は FDT5 を使用
※haXe 自体はインストール済という前提で書いていきます。

jQueryExtern を利用

jQueryExtern という、jQueryラッパーライブラリがあります。
※いわゆる「コンパイルを通すためだけのjQuery型指定のみが記述されたライブラリ」みたいな物。
この利用方法は下記2つです。

[利用方法 1]

jQueryExternForHaxe [GitHub]からダウンロード。

解凍したフォルダ内、下記2ファイルをプロジェクト ソースフォルダにコピー

  • JQuery.hx
  • jQuery フォルダ

これでパスが通りました。

※ソースフォルダじゃなく、任意のフォルダ(例えば”Hoge/以下”)に配置したい!という場合には、.hxml に -cp Hoge を追記するとパスが通ります。

[利用方法 2]

haxelib に jQueryExtern を installします。

ターミナルで

$ haxelib install jQueryExtern

と打つだけでインストールできます。

※ 下記のようなメッセージが出たら haxelib のセットアップがまだ済んでいないので、haxelib setupを参考に、済ませたあと再度インストールしましょう。
This is the first time you are runing haxelib. Please run haxelib setup first

次に、haxelibにインストールしたjQueryExternにパスを通します。
.hxml に -lib jQueryExternを追記。

jQueryを動かしてみる

jQueryExtern (というかhaXeのJSライブラリはすべて?) は、コンパイルを通すためにあくまで型を指定しているだけ、なので、実際のjQueryをダウンロードし、htmlからリンクして実態を用意しておきます。

次に .hx ファイルで

import JQuery;

とインポートすると、例えば下記のようにnew jQuery() を利用できます。

button1 = new JQuery("#button1");

サンプル

動作サンプル

ソース全体としては下記。

index.html

1
2
3
4
5
6
7
8
9
10
<!DOCTYPE html>
<html lang="en">
	<head>
		<title>TestHaxeJQuery</title>
		<script type="text/javascript" src="js/jquery-1.7.1.js"></script>
	</head>
	<body>
		<div id="button1" style="width:150px;height:30px;background-color:#aaa;">button1</div>
		<script type="text/javascript" src="js/App.js"></script>
</html>

Main.hx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import JQuery;
import js.Lib;
class Main {
 
	var button1:JQuery;
 
	static public function main():Void {
		new Main();
	}
 
	public function new(){
		js.Lib.window.onload = onLoaded;
	}
 
	/**
	 * window onloaded
	 */
	private function onLoaded(e:Dynamic){
		setButton();
	}
 
	/**
	 * button setting
	 */
	private function setButton():Void{
		button1 = new JQuery("#button1");
		button1.cssSet("cursor","pointer");
		button1.click(onButtonClick);
		button1.hover(onButtonRollOver);
		button1.mouseout(onButtonRollOut);
	}
 
	/**
	 * button events
 	 */	
	private function onButtonClick():Void{
		js.Lib.alert("clicked");
	}
 
	private function onButtonRollOver():Void{
		button1.cssSet("background-color","#ccc");
	}
 
	private function onButtonRollOut():Void{
		button1.cssSet("background-color","#aaa");
	}
}

最後に

それ違うよ!などツッコミありましたらぜひよろしくお願いします。

参考

Using jQuery in haXe | Andy Li's Blog
haXe in action, check out a sample haXe project in FDT 5
Complex HaXe example
八角研究所 : Series: クライアント(ブラウザ)もサーバも同一言語で書ける haXe を使ってみる «


レンタルサーバー豆知識