Knockout JS - viewModel access
I'm writing an application for making a reservation. The reservation procedure is rather complex and has quite some dependencies so I decided to use knockout to help me observe changes and update the UI.
I started implementing the customer list. The first customer in the form will be the one who has to enter his details, the others only need names. I figured I could just add a dependentObservable that checks if the current customer is the first one in the customers array to decide whether to display the additional fields.
The problem is that when trying to access viewModel from a customer, I get only get 'undefined'. I tried passing a reference to viewModel to the customer, but that didn't work either. What am I doing wrong? Can viewModel not 开发者_Go百科be accessed?
Here's the code:
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);
I figured it out. The idea of passing the viewModel to the customer was the right one, just the execution was bad. When I initialized customers I did it with a new customer, which in turn looked for customers which was not there yet.
Here's the working code:
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);
精彩评论