ProtoViewLogic: message()
ProtoViewLogic へ送るメッセージを生成します。
構文
protoViewLogic.message(id, code, param) => object
引数
-
id:string(省略可)メッセージの識別子です。
-
code:string(省略可)メッセージの追加の識別子です。
-
param:any(省略可)メッセージに含めるパラメータです。
返値: object
引数と自身をまとめたメッセージオブジェクトです。
-
id:string|null引数で与えられた文字列です。指定がなかった場合、
nullとなります。 -
code:string|null引数で与えられた文字列です。指定がなかった場合、
nullとなります。 -
param:any引数で与えられた任意の値を持ちます。指定がなかった場合、
nullとなります。 -
origin:thismessage()の対象のProtoViewLogic自身です。
例
メッセージ作成の例です。
import { ProtoViewLogic } from "/alier_sys/ProtoViewLogic.js";
const vl = new class MyProtoViewLogic extends ProtoViewLogic { /* ... */ }
vl.message("cat", null, null);
// => { id: "cat", code: null, param: null, origin: vl }
vl.message("dog", "bow", null);
// => { id: "dog", code: "bow", param: null, origin: vl }
vl.message("cat", null, { breed: "calico" });
// => { id: "cat", code: null, param: { breed: "calico" }, origin: vl }
メッセージ処理中に他のメッセージを送出する複雑な例です。
import { ProtoViewLogic } from "/alier_sys/ProtoViewLogic.js";
const flat = new class Flat extends ProtoViewLogic {
async messageHandler(msg) {
msg.deliver({
tom: (msg) => {
return msg.deliver({
chase: (msg) => {
console.log("Tom chases Jerry.");
return this.post(this.message("jerry", "run", null));
},
fall: (msg) => {
console.log("Tom falls onto the earth.");
return this.post(this.message("jerry", "farewell", null));
},
});
},
jerry: (msg) => {
return msg.deliver({
run: (msg) => {
console.log("Jerry runs away.");
return this.post(this.message("tom", "fall", null));
},
farewell: (msg) => {
console.log("Jerry casts a farewell to Tom.");
},
});
},
});
}
};
flat.post(flat.message("tom", "chase"));
// ==> 以下の順にログが表示される:
// - "Tom chases ..."
// - "Jerry runs ..."
// - "Tom falls ..."
// - "Jerry casts ..."
解説
生成したメッセージは post() の引数として利用されます。post() の呼び出し先の ProtoViewLogic にメッセージ処理を依頼できます。
引数 message のプロパティ id や code には任意の文字列を指定することができます。
これらの文字列はメッセージを処理する ProtoViewLogic が持つ messageHandler() の中で、メッセージの種別を識別するために利用できます。
addActiveEvents() などで追加されたイベントリスナーから送られるメッセージには、id や code としてそのイベントの発生源である要素を参照するプロパティ名とイベント種別がそれぞれ id と code に設定されています。