2014-01-21 125 views
0

我有一個ViewModel,它是一個可觀察的對象數組,它包含我將使用foreach輸出的聯繫人信息。我需要有一個計算的觀測值依賴於firstName和每個聯繫人的lastNameknockoutjs - 可觀察數組內部的可觀測值

var contacts = ko.observableArray([ 
    { 
     firstName: ko.observable("Jim"), 
     lastName: ko.observable("Carrey"), 
     fullName: ko.computed(function(){ 
      return this.firstName() + " " + this.lastName(); 
     }, this), 
     image:  ko.observable("images/jim.jpg"), 
     phones: ko.observableArray([ 
      {type: ko.observable("Mobile"), number: ko.observable("(555) 121-2121")}, 
      {type: ko.observable("Home"), number: ko.observable("(555) 123-4567")} 
     ]) 
    }, 
    ...//other objects of the same structure 
]); 
ko.applyBindings(contacts); 

,但我得到這個錯誤Uncaught TypeError: Object #<HTMLDocument> has no method 'firstName'。有人可以解釋爲什麼我對this.firstName()的引用失敗嗎?謝謝。

+0

你能把小提琴嗎? – DevelopmentIsMyPassion

+0

http://jsfiddle.net/arrustamyan/kD83g/ –

+0

在obs數組內使用計算函數的任何原因? – DevelopmentIsMyPassion

回答

1

問題是您的聯繫人定義中的this未引用聯繫人本身;它指的是全局對象。使用函數(「經典」構造函數或簡單的創建對象字面值並返回它的函數)來創建聯繫人,以便它可以正確設置其上下文。

+0

我無法理解的是爲什麼'this'沒有指向當前對象?有沒有我可以閱讀的文檔? –

+0

你可以試試https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/這個 – ebohlman

+0

[參考](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#Function_context)說:「當一個函數被調用爲一個對象的方法時,它被設置爲該方法被調用的對象。」這是否意味着如果我打電話ko.computed沒有第二個參數像這樣'fullName:ko.computed(function(){ return this.firstName()+「」+ this.lastName(); }),'then'這'會引用我的聯繫人對象? –