[英]Knockout JS - viewModel access
我正在寫一個預訂申請。 預訂過程相當復雜,並且有相當多的依賴關系,所以我決定使用敲除來幫助我觀察變化並更新 UI。
我開始實施客戶名單。 表格中的第一個客戶將是必須輸入其詳細信息的客戶,其他客戶只需要姓名。 我想我可以添加一個dependentObservable 來檢查當前客戶是否是customers 數組中的第一個來決定是否顯示其他字段。
問題是,當嘗試從客戶那里訪問 viewModel 時,我只會得到“未定義”。 我嘗試將 viewModel 的引用傳遞給客戶,但這也不起作用。 我究竟做錯了什么? 不能訪問viewModel嗎?
這是代碼:
var customer = function(){
this.firstName = ko.observable('');
this.lastName = ko.observable('');
this.fullName = ko.dependentObservable(
function(){
return this.firstName() + " " + this.lastName();
},
this
);
this.gender = ko.observable('');
this.diet = ko.observable('');
this.primaryCustomer = ko.dependentObservable(
function(){
console.log(viewModel);
return viewModel.customers.indexOf(this) == 0;
},
this
);
this.email = ko.observable('');
}
var viewModel = {
customers: ko.observableArray([new customer()]),
addCustomer: function(){
this.customers.push(new customer());
},
removeCustomer: function(customer){
this.customers.remove(customer);
}
}
ko.applyBindings(viewModel);
我想到了。 將 viewModel 傳遞給客戶的想法是正確的,只是執行很糟糕。 當我初始化客戶時,我與一個新客戶一起做,這反過來又尋找尚未存在的客戶。
這是工作代碼:
var customer = function(viewModel){
this.firstName = ko.observable('');
this.lastName = ko.observable('');
this.fullName = ko.dependentObservable(
function(){
return this.firstName() + " " + this.lastName();
},
this
);
this.gender = ko.observable('');
this.diet = ko.observable('');
this.primaryCustomer = ko.dependentObservable(
function(){
console.log(viewModel);
return viewModel.customers.indexOf(this) == 0;
},
this
);
this.email = ko.observable('');
}
var viewModel = {
customers: ko.observableArray(),
removeCustomer: function(customer){
this.customers.remove(customer);
}
}
viewModel.customers.push(new customer(viewModel));
viewModel.addCustomer = function(){
viewModel.customers.push(new customer(viewModel));
}
ko.applyBindings(viewModel);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.