私はjQueryでパブリッシャー/サブスクライバーデザインパターンのフォームを実装してきました。私は基本的に、ページのコンポーネントとして機能するCoffeeScriptを利用してJavascriptでクラスを構築しています。つまり、ナビゲーション、データリストなど。
DOM要素にイベントを発生させる代わりに、トリガーを使用してカスタムイベントを送信するこれらのクラスのインスタンスがあります。これらのインスタンスは、相互にリッスンし、相互の動作の変更に基づいて、所有するDOM要素を適宜更新できます。
コンポーネントの1つがカスタムイベントを適切にディスパッチしているので、これが機能することはわかっています。しかし、私は障害に遭遇しました。私は別のコンポーネントを作成しましたが、私の人生の間、なぜそれがイベントが発生しないのか理解できません。
これは私のクラスの実装です:
window.List = (function() {
List = function(element, settings) {
var _a, _b, _c;
this.list = $(element);
this.settings = jQuery.extend(List.DEFAULTS, settings);
this.links = this.list.find(this.settings.link_selector);
this.links.selectable();
_b = [SelectableEvent.COMPLETED, SelectableEvent.UNDONE, SelectableEvent.SELECTED, SelectableEvent.DESELECTED];
for (_a = 0, _c = _b.length; _a < _c; _a++) {
(function() {
var event_type = _b[_a];
return this.links.bind(event_type, __bind(function(event, selectable_event) {
return this.dispatch(selectable_event);
}, this));
}).call(this);
}
return this;
};
List.DEFAULTS = {
link_selector: "a",
completed_selector: ".completed"
};
List.prototype.change = function(mode, previous_mode) {
if (mode !== this.mode) {
this.mode = mode;
if (previous_mode) {
this.list.removeClass(previous_mode);
}
return this.list.addClass(this.mode);
}
};
List.prototype.length = function() {
return this.links.length;
};
List.prototype.remaining = function() {
return this.length() - this.list.find(this.settings.completed_selector).length;
};
List.prototype.dispatch = function(selectable_event) {
$(this).trigger(selectable_event.type, selectable_event);
return alert(selectable_event.type);
};
return List;
}).call(this);
注意を払う:
List.prototype.dispatch = function(selectable_event) {
$(this).trigger(selectable_event.type, selectable_event);
return alert(selectable_event.type);
};
このコードは適切にトリガーされ、アラートを介して予想されるイベントタイプを返します。ただし、アラートの前に、それ自体でカスタムイベントをトリガーすることが期待されます。これが私の問題に直面しているところです。
$(document).ready(function() {
var list_change_handler, todo_list;
todo_list = new List("ul.tasks");
list_change_handler = function(event, selectable_event) {
return alert("Hurray!");
};
$(todo_list).bind(SelectableEvent.COMPLETED, list_change_handler);
$(todo_list).bind(SelectableEvent.UNDONE, list_change_handler);
$(todo_list).bind(SelectableEvent.SELECTED, list_change_handler);
$(todo_list).bind(SelectableEvent.DESELECTED, list_change_handler);
}
ここにアラート「Hurray」が表示されますが、残念ながらここでは運がありません。皮肉なことに、カスタムイベントをディスパッチするのと同じ方法で実装された別のクラスでまったく同じことを実行しましたが、リスナーはそれを問題なく受信しています。これがうまくいかない理由について何かアイデアはありますか?
アップデート:
コメントで説明しているように、コンソールに「this」を記録すると、クラスを表すJSオブジェクトが返されるように見えます。ただし、「$(this)」をログに記録すると、空のjQueryオブジェクトが返されるため、トリガーが起動されることはありません。「this」がクラスのインスタンスを正確に返しているのに、なぜ$(this)が空になるのかについて何か考えはありますか?