2011-07-13 11 views
2

私は予約をするためのアプリケーションを書いています。 予約手順はかなり複雑で、かなりの依存関係がありますので、ノックアウトを使用して変更を観察し、UIを更新することにしました。ノックアウトJS - viewModelアクセス

私は顧客リストの実装を開始しました。フォームの最初の顧客は自分の詳細を入力する必要があり、他の顧客は名前が必要です。 私は、現在の顧客が追加のフィールドを表示するかどうかを決定するためにcustomers配列内の最初のものであるかどうかを調べるdependentObservableを追加するだけでよいと考えました。

問題は、顧客からviewModelにアクセスしようとすると「undefined」しか得られないということです。 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); 

答えて

5

私はそれを考え出しました。 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); 
関連する問題