我開始使用jquery和Model View ViewModel,並遇到與事件處理程序附件on()一起使用的問題。 我第一類是TicTacToeModel它操作一個井字遊戲記憶:訪問方法時遇到問題
var TicTacToeModel = function() {
Observable.call(this);
this.grid = new Array(3);
for (let i = 0; i < this.grid.length; ++i) {
this.grid[i] = new Array(3);
}
};
//Some prototype function
//...
我有另一個類,TicTacToeController依賴於第一類和管理遊戲的圖形部分與DOM的操作:
var TicTacToeController = function(game, selector) {
this._element = $(selector);
this._model = game;
this._template = Handlebars.compile(view);
this.addListeners();
this.render();
};
(遊戲聲明:game = new TicTacToeModel();
)
所以在我的第二類我有這樣的功能:
TicTacToeController.prototype.addListeners = function() {
this._model.on('change', this.render, this);
this._model.play(0,0);//works
this._element.on('click', "td", function() {
this._model.play(0,0);//doesn't work
});
};
當我單擊我的圖形界面中的單元格時,我想在單元格(0,0)中調用play()函數(函數play會更新內存中的遊戲),但我無法在.on()。但是,這似乎是在.on()函數以外的工作,所以我認爲造成該問題的this
的壞利用率。
感謝您的回答,但工作正常,但如果我添加一些jquery到這樣的功能:'TicTacToeTlerController.prototype.addListeners = function(){ this._model.on('change',this.render,this ); (「click」,「td」,function(){ $(this).addClass(「case」); $(this).html(「X」); this._model。 play(0,0); //不起作用 } .bind(this)); };'jquery不被考慮,你有任何想法來解決它? – Lodec
不確定你的意思是「jquery沒有被考慮到」,但是你試過'$(this._element)...'而不是'$(this)...'嗎? – Jack
'$(this._element)'不起作用,因爲它會改變我的整個網格,但如果我在以下內容中添加參數「event」:this._element.on('click',「td」,function(event){ ...}',event.target可以工作,但爲什麼我不能使用'$(this)',而它代表.on()函數的「td」元素? – Lodec