インプレース編集コンポーネントの要件定義
インプレース編集の基本的な動作要件は以下の通りです:
- 初期表示:テキスト要素(例:<span>)で表示
- クリック操作:編集モードに移行し、入力フィールドと操作ボタンを表示
- 保存処理:更新内容を反映し通常表示に復帰
- キャンセル:元の値に戻し通常表示に復帰
オブジェクト指向設計
コンストラクタ関数とプロトタイプパターンを使用してコンポーネントを実装します。
class InPlaceEditor {
constructor(config) {
this.elementId = config.id;
this.initialValue = config.value || 'デフォルトテキスト';
this.container = config.parent;
this.elements = {
wrapper: null,
display: null,
input: null,
actions: []
};
this.initialize();
}
}
DOM構築処理
メモリ内でDOM構造を構築し、最後に一括でマウントします。
initialize() {
this.buildStructure();
this.setupEventListeners();
this.render();
}
buildStructure() {
const wrapper = document.createElement('div');
wrapper.id = this.elementId;
const displayElement = document.createElement('span');
displayElement.textContent = this.initialValue;
wrapper.appendChild(displayElement);
const inputElement = document.createElement('input');
inputElement.type = 'text';
inputElement.value = this.initialValue;
wrapper.appendChild(inputElement);
// 操作ボタン群
const buttons = ['保存', 'キャンセル'].map(label => {
const btn = document.createElement('button');
btn.textContent = label;
wrapper.appendChild(btn);
return btn;
});
this.elements = {
wrapper,
display: displayElement,
input: inputElement,
actions: buttons
};
this.container.appendChild(wrapper);
}
状態管理
表示状態を切り替えるためのメソッド群:
switchToText() {
this.elements.input.style.display = 'none';
this.elements.display.style.display = 'inline';
this.elements.actions.forEach(btn => btn.style.display = 'none');
}
switchToEdit() {
this.elements.input.style.display = 'inline';
this.elements.display.style.display = 'none';
this.elements.actions.forEach(btn => btn.style.display = 'inline');
this.elements.input.value = this.initialValue;
}
イベント処理
アロー関数を使用してコンテキストを保持:
setupEventListeners() {
this.elements.display.addEventListener('click', () => {
this.switchToEdit();
});
this.elements.actions[0].addEventListener('click', () => {
this.saveChanges();
});
this.elements.actions[1].addEventListener('click', () => {
this.cancelEdit();
});
}
使用例
const editor = new InPlaceEditor({
id: 'editable-text',
value: '編集可能なテキスト',
parent: document.getElementById('app')
});