我想讓我的淘汰賽腳本更有條理,此外,我想避免將兩個函數命名爲偶然事件。所以我在想,如果我能像這樣同一個函數嵌套的ViewModels(我一直是真的簡單):Fiddle在knockout.js中使用多視圖模型
這裏的HTML
<p>First name: <strong data-bind="text: other.firstName">todo</strong></p>
<p>Last name: <strong data-bind="text: other.lastName">todo</strong></p>
<p>Full name: <strong data-bind="text: other.fullName">todo</strong></p>
和JS:
function AppViewModel() {
var self = this;
self.other = {
firstName: ko.observable("Bert"),
lastName: ko.observable("Bertington"),
/*fullName: ko.computed(function(){
return this.firstName + " " + this.lastName;
}, this)*/
}
}
這工作正常,但如果我取消註釋ko.computed,它會崩潰。有沒有什麼辦法可以用這種方式來組織我的淘汰賽,爲什麼計算機會崩潰,是否有任何方法來編寫ko.computed函數,以便它可以工作?
編輯:問題#2
如果我有一個表格任何形式是這樣的:
<form data-bind="submit: other.otherSubmit" data-ajax="false">
<button type="submit">Submit</button>
</form>
,我添加處理程序提交,像這樣:
// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function AppViewModel() {
var self = this;
self.other = new function(){
var self = this;
self.firstName = ko.observable("Bert");
self.lastName = ko.observable("Bertington");
self.fullName = ko.computed(function(){
return self.firstName() + " " + self.lastName();
});
self.otherSumbit = function(){}
}
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
爲什麼錯誤控制檯是否返回:
該值的提交綁定必須是一個函數
謝謝你兩個事實證明,我寫的程序中缺少的是我寫了self.other = function(){...而不是self.other = new function(){... the 「新」基本上使我的整個計劃正常工作 – 2013-02-21 13:42:59