2016-11-23 102 views
1

我开始使用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的坏利用率。

回答

1

你需要使用这样的bind

更改此:

this._element.on('click', "td", function() { 
    this._model.play(0,0);//doesn't work 
}); 

到:

this._element.on('click', "td", function() { 
    this._model.play(0,0); //should now work 
}.bind(this)); 
+0

感谢您的回答,但工作正常,但如果我添加一些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

+0

不确定你的意思是“jquery没有被考虑到”,但是你试过'$(this._element)...'而不是'$(this)...'吗? – Jack

+0

'$(this._element)'不起作用,因为它会改变我的整个网格,但如果我在以下内容中添加参数“event”:this._element.on('click',“td”,function(event){ ...}',event.target可以工作,但为什么我不能使用'$(this)',而它代表.on()函数的“td”元素? – Lodec

0

你是不是在同一个范围内,这是不一样的这个变量调用播放方法,当你使用。 一个肮脏的解决办法可能是

let _model = this._model 
this._element.on('click', "td", function() { 
     _model.play(0,0);//work! 
    }); 

但正如说,这是一个肮脏的解决办法,也许别人可以解释,但基本上认为这会产生内存泄漏。也许解决办法是在同一类的使用方法和实例传递给click方法,种:

TicTacToeController.prototype.click = function() ... 
... 
this._element.on('click', "td", this.click); 

认为这应该做的伎俩,但我必须承认我不是一个js专家。

+1

我以为也使用这种肮脏的解决方法,但我知道有更好的方法来解决我的问题^^。 – Lodec