我开始使用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