‘javascript’ タグのついている投稿

ExternalInterface

2009年9月12日 土曜日

一つ前のエントリで取り上げたlog.asの実装のこの部分。

25
26
27
28
29
30
31
32
33
34
35
36
37
        try {       
          ExternalInterface.call(<><![CDATA[
              (function(obj, klassName) {
               obj.toString = function() { return klassName };
               console.log(obj);
               ;})  
              ]]></>.toString(),
              ObjectUtil.clone(arg),
              getQualifiedClassName(arg)
              );    
        } catch(e:Error) {
          ExternalInterface.call('console.log', r);
        }

ExternalInterface.callの第一引数がなんか見慣れない書式。
なんかオブジェクトつくってtoStringしてる?
調べてみた。

package {
  import flash.display.*;
  public class Hello extends Sprite {
    public function Hello(){
      var hoge:Object = <><![CDATA[
        (function(obj, klassName) {
         obj.toString = function() { return klassName };
         console.log(obj);
         ;})
        ]]></>;
      log(hoge);
      log(hoge.toString()); 
    } 
  }
}

ピクチャ 3
なるほどー。CDATAセクションのみのXMLListオブジェクトつくってtoStringしてるんですね。それにしても変わった書式。

というか、ExternalInterface.callの第一引数、evalしたときに関数になってたら何でもokなんすね。
これならjs,flashの連携が楽にできそ。

JSDeferred

2009年5月8日 金曜日

JSDeferredとは?

JSDeferredはcho45さんがモチキのDeferred機構に影響されて作ったらしいJavascript用の非同期処理ライブラリで、煩雑になりがちな複数の非同期処理間の協調動作を、簡単かつ柔軟に記述できるステキングなライブラリ
引用:http://unsigned.g.hatena.ne.jp/Trapezoid/20080425/1209054401

desu。

非同期処理

そもそも非同期処理とはどのようなものかといいますと、XHRリクエストがそのひとつです。
この例では、1,2,3の順に処理が実行されます。なれればなんてことないですが、処理順序が逆転していることがわかります。

1
2
3
4
5
console.log("1");
var myAjax = new Ajax.Request(url, {
				method: 'get',
				onComplete: function(res){ console.log("3");}});
console.log("2");

もうすこし複雑な例。

1
2
3
4
5
6
7
8
9
10
11
12
13
new Ajax.Request(url, {
  method: 'get',
  onComplete: function(res){
    console.log(res);
 
    new Ajax.Request(url2,{
      method: 'get',
      onComplete:function(res2){
        console.log(res2);
      }
    });
  }
});

うーん、もう処理順序がぐちゃぐちゃで処理を追いづらいですね。。

JSDeferredをつかうと。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
ajax_request(url).
next(function(res){
 console.log(res);
}).ajax_request(url2).
next(function(res2){
 console.log(res2);
});
 
vaf ajax_request = function(url){
    var d=new Deferred();
    new Ajax.Request(url,{
      method: 'get',
      onComplete:function(res){
        d.call(res);
      }
    });
    return d;
}
Deferred.register('ajax_request',ajax_request);

だいたいこんな感じに書けます。(直接ここに書いたので間違ってるかもしれません^^;)
ちゃんと上から順に実行されていくので、処理の流れを理解しやすいですね!

しくみ

ソースよんでくらはいw
短いですが、javascriptのエッセンスがつまっていてとても勉強になると思います。

参考:

http://d.hatena.ne.jp/amachang/20060910/1157911122

http://labs.gmo.jp/blog/ku/2007/09/firefoxsettimeout.html

http://ido.nu/kuma/2007/11/29/coding-synchronized-asynchronous-processing-intuitively-with-mochikit-async-deferred/

http://d.hatena.ne.jp/amachang/20080303/1204544340

http://d.hatena.ne.jp/amachang/20061129/1164799871