1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

javascriptのProxyパターン

Posted at

Proxy パターン

Proxy とは 「代理(人)」 という意味です。
Proxyパターンはプログラミングにおけるデザインパターンの一種。既存クラスのメソッドが呼ばれた際に、一旦中間的な処理を実行してから渡すパターンです。

// 画像読み込んで、画面に表示用メソッド
var imgFunc = (function() {
    var imgNode = document.createElement('img');
    document.body.appendChild(imgNode);
    return {
        setSrc: function(src) {
            imgNode.src = src;
        }
    }
})();

// 代理メソッド
var proxyImage = (function() {
    var img = new Image();
    img.onload = function() {
        imgFunc.setSrc(this.src); // 画像読み込みが完了したら、画像を設定
    }
    return {
        setSrc: function(src) {
            imgFunc.setSrc('./loading.gif'); // 画像読み込み完了までローディング画像を表示させ
            img.src = src;
        }
    }
})();

proxyImage.setSrc('./pic.png');
  1. 代理メソッドproxyImageを呼び込んで、[./pic.png]を読み込み開始
  2. ./pic.pngが読み込み完了までローディング画像./loading.gifを表示させる
  3. ./pic.pngが読み込み完了したら、画像がimgNodeにセット(imgFunc.setSrc(this.src)で)され、画面に表示

この例でProxyパターンを使うことで画像遅延読み込みを実現することができます。

参考

1.zeng tan.2015. Design Pattern And Development Practice Of JavaScript

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?