2016-11-23 96 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