ObservableObject
モジュールパス: /alier_sys/ObservableObject.js
|
コンストラクタ
バインディングソースとなるオブジェクトを生成します。
構文
new ObservableObject(data, allowsTowWay) => Proxy
引数
-
data
:Object
同期対象とするプロパティ名と初期値の組のオブジェクトです。
-
allowsTwoWay
:boolean
双方向のバインドを許可するか否かです。
true
なら双方向バインディングを許可し、false
なら許可しません。コンストラクト後、この値はメンバ変数allowsTwoWay
として参照できます。
返値: Proxy
このオブジェクトのプロキシ―です。プロパティ値を更新すると同期設定されたターゲットオブジェクトの値も更新されます。
例
// モジュールのインポート
import { ObservableObject } from "/alier_sys/ObservableObject.js";
const source1 = new ObservableObject({ x: 1 }, true);
const source2 = new ObservableObject({ x: 2 }, false);
console.log(source1.x)
// => 1
console.log(source2.x)
// => 2
解説
生成されたオブジェクトは引数 data
が持つ列挙可能なプロパティの浅いコピーを持ちます。
引数 allowsTwoWay
の値は生成されたオブジェクトの同名のプロパティ allowsTwoWay
の値として使用されます。 allowsTwoWay
が false
なら単方向バインディングのみ、true
なら双方向バインディングとなります。
メソッド
bindData()
- 引数で渡されたオブジェクトをバインディングターゲットとして登録します。
reflectValues()
- プロパティの状態を更新します。
curateValues()
- 監視しているプロパティと現在の値を収集します。
プロパティ
allowsTwoWay
このプロパティは読み取り専用です。
双方向バインディングを許可するかどうかです。単方向になるとバインド元となるソースから bindData()
でバインドされたターゲットにのみ値の更新が反映されます。単方向でターゲットの値を更新すると、ソースの値で上書きされます。
型
boolean
双方向を許可する場合は true
、許可しない場合は false
です。
例
// ターゲットのプロトタイプ定義
const target_proto = {
reflectValues(valueMap) {
const updated_values = {};
for (const k of Object.keys(this)) {
if (!(k in valueMap) || typeof valueMap[k] !== typeof this[k]) {
continue;
}
const v = valueMap[k];
this[k] = v;
updated_values[k] = v;
}
this.source.reflectValues(updated_values);
},
onDataBinding(source, twoWay) {
this.source = source;
this.reflectValues(source.curateValues());
}
};
// ObservableObject でバインドする対象の用意
const target_0 = Object.assign(Object.create(target_proto), { x: 14, y: 57 });
const target_1 = Object.assign(Object.create(target_proto), { x: 1729, z: 137 });
const target_2 = Object.assign(Object.create(target_proto), { y: 3.14159, z: 2.71828 });
// ObservableObject の生成
// oo_oneway.allowsTwoWay を false に設定
const oo_oneway = new ObservableObject({ x: 42 }, false);
// oo_twoway.allowsTwoWay を true に設定
const oo_twoway = new ObservableObject({ y: 57 }, true);
// target_0 を oo_oneway にバインド
// (既定動作: oo_oneway.allowsTwoWay に従う; 単方向バインディング)
oo_oneway.bindData(target_0);
// => true; バインド成功
// target_1 を oo_oneway に単方向バインド
oo_oneway.bindData(target_1, false);
// => true; バインド成功
// target_2 を oo_oneway に双方向バインド
oo_oneway.bindData(target_2, true);
// => true; バインド成功するが、単方向でバインドされる
// target_1 を oo_twoway に単方向バインド
oo_twoway.bindData(target_1, false);
// => false; バインド失敗。既に他のソースとバインドしている。
// target_2 を oo_twoway に双方向バインド
oo_twoway.bindData(target_2, true);
// => true; バインド成功