2
3

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.

状態変更とは

GUIが絡むプログラミングでは頻繁に記述すると思いますが、最近はいろいろなライブラリ内に隠蔽されているベースな部分だと思います。基本的にはObserverパターンをしようします。

ObserverパターンはGUIプログラミンでは頻繁に使用するので初耳の方はこちらを確認してください。

状態変更でよく使うのは、A状態に変更されたら、各オブジェクトがそれぞれ処理を実行するというものです。

例:
Formの確認ボタンが押されたら"確認画面に移動"、"送信ボタンを表示する"など...

実装

Monitor.js

Monitor = function(){

};

Monitor.prototype['addListener'] = addListener;
Monitor.prototype['changeState'] = changeState
Monitor.prototype['notify']      = notify;

Monitor.listeners = {}; // リスナー

function addListener(state, scope, func){
    if(Monitor.listeners[state] == undefined ) Monitor.listeners[state] = [];
    Monitor.listeners[state].push({scope: scope, func: func});
}

function changeState(state){
    if(Monitor.listeners[state] == undefined ) throw new Error("指定された状態は存在しません。");
    this.notify(state);
}

/**
 * 通知処理
 */
function notify(state){
    for(var i = 0; i < Monitor.listeners[state].length; ++i){
        var obj = Monitor.listeners[state][i];
        obj.func.apply(obj.scope);
    }
}

次にStateクラスを定義します。

state.js

State = function(){

};

State.current = State.ON_EDIT;

State.ON_EDIT            = 0;
State.ON_CONFIRM         = 1;
State.ON_COMPLETE        = 2;
State.ON_VALIDATE        = 3;
State.ON_SENDMAIL        = 4;
State.ON_SYSTEM_ERROR    = 99;

使い方

main.js

var monitor = new Monitor();
monitor.addListener(State.ON_EDIT, this, this.onEdit);

// エディット処理
function onEdit(){
	console.log(" ON_EDITで処理実行");
}


// 状態変更
monitor.changeState(State.ONEDIT);

2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?