[英]viewModel computed functions on the prototype using knockout.js
我正在使用基因敲除庫,它有助於數據綁定。 因此,我不斷收到這樣的錯誤消息:我的變量未在viewModel原型上的計算函數內定義。 我知道這是因為計算函數正在將“ this”的上下文更改為Window,但是我似乎無法弄清楚如何將其更改回root(viewModel)。我所指的方法是JavaScript中的“消息”。 話雖這么說,我如何將上下文更改回viewModel?
這是我的代碼:
HTML
p#title.col-xs-12.bg-primary.text-center
| Tic - Tac - Toe!
div.col-xs-3.bg-info
div.bg-primary.controls
span
button.btn.btn-default(data-bind="click:StartMessage.bind($root)")
| New Game
p#message.lead(data-bind="text:Messages.bind($root)()")
table.bg-success(style="table-layout:fixed;")
tr#row1
td(data-bind="click:Messages.bind($root)")
td  
td  
tr#row2
td  
td  
td  
tr#row3
td  
td  
td  
JAVASCRIPT
var message = (function(){
function Message(){
this.main = ko.observable(true);
this.welcome = "Welcome to Tic-Tac-Toe! This is a 2 player game. Click New Game to play!"
this.turn = ", its your turn."
this.win = ", you won!"
this.draw = "It's a draw..."
}
return Message;
})()
var players = (function(){
function Players(){
this.player1 = ko.observable(true);
this.player2 = ko.observable(false);
}
return Players;
})()
var aBox = (function(){
function ABox(){
this.symbol = ko.observable(" ")
}
return ABox;
})()
var viewModel = (function(){
function ViewModel(){
this.GameMessage = new message();
this.thePlayers = new players();
this.r1c1 = new aBox();
this.r1c2 = new aBox();
this.r1c3 = new aBox();
this.r2c1 = new aBox();
this.r2c2 = new aBox();
this.r2c3 = new aBox();
this.r3c1 = new aBox();
this.r3c2 = new aBox();
this.r3c3 = new aBox();
}
/****************************************
************* Messages *****************
****************************************/
ViewModel.prototype.StartMessage = function(){
this.GameMessage.main(false)
}
ViewModel.prototype.Messages = ko.computed(function(){
if(this.GameMessage.main()){
return this.GameMessage.welcome;
}
else if(this.thePlayers.player1()){
this.thePlayers.player1(false);
this.thePlayers.player2(true);
return "Player 1"+this.GameMessage.turn;
}
else if(this.thePlayers.player2())
this.thePlayers.player1(true);
this.thePlayers.player2(false);
return "Player 2"+this.GameMessage.turn;
},ViewModel)
return ViewModel;
})()
ko.applyBindings(new viewModel())
我已經嘗試過將上下文更改為所示的“ viewModel”,$ root和“ this”。
如果您想知道該方法要完成什么,請單擊“新消息”按鈕,它將觸發顯示一條消息。 然后,如果單擊<td>
,它將在前一個消息的位置顯示另一條消息。
ko.computed函數包含第二個參數,該參數允許將計算函數綁定到您指定的任何對象 。 (它在幕后僅使用apply )
因此,當您在原型中定義計算式時,只需將計算式綁定到this
,就像這樣:
ViewModel.prototype.Messages = ko.computed(function(){
// your function code
}, this);
請記住,在使用原型時, this
是指您感興趣的對象實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.