2

我有一個非常簡單的例子,它不工作。Knockout.js:函數參數undefined

的jsfiddle:http://jsfiddle.net/ThomasDeutsch/8hzhp/3/

// My Model 
function Customer(id, name, lastname) { 
    this.Id = ko.observable(id); 
    this.Name = ko.observable(name); 
    this.LastName = ko.observable(lastname); 
} 

// My ViewModel 
ViewModel = (function() { 
    var getName = ko.computed(function (x) { 
     return x.Name(); 
    }); 

    return { 
     getName: getName(new Customer(1, "Thomas", "D")) 
    }; 
})(); 

ko.applyBindings(ViewModel);​ 

問題:參數(X)是未定義

目標:返回調用的對象的名稱 - 屬性 - 我想用X作爲屬性,以便我可以用任何具有可觀察名稱屬性的對象調用此函數

代碼說明: 這是通過knockout.js使用揭示模塊模式完成的。 Name屬性是一個ko.observable() - 所以需要()。

問題:爲什麼x undefined?

回答

3

讓我問你。你認爲x在哪裏定義?

您正在調用getName並傳遞一個Customer,但getName不指望參數。

如果重寫功能,這樣它會工作:

var getName = function(x) { return ko.computed(function() { 
    return x.Name(); 
})}; 
+0

現在我明白了!保護你。我認爲我可以使用ko.computed函數作爲參考。好吧,因爲Name屬性已經是一個ko.observable函數,我不需要ko.computed - >結果:http://jsfiddle.net/ThomasDeutsch/8hzhp/6/ –

+0

正如你現在正在返回一個可觀察的,你也可以刪除()並且只是:'return x.Name;'。文本綁定知道如何使用observable。 –

+0

好極了。這就對了 –

1

你試圖改變觀察的「的getName」的價值,但因爲它是一個計算的一個,直到你指定的不確定行爲這應該如何處理。

我認爲最好的解決方案是引入另一個存儲客戶的observable。

var ViewModel = (function() { 
    // Observable for the customer 
    var customer = ko.observable(new Customer(1, "Thomas", "D")); 

    // The computed observable, using the other one 
    var getName = ko.computed(function() { 
     return customer().Name(); 
    }); 

    // If you only need to access the name, its sufficient 
    // to export only that observable. However, this is still 
    // read-only. 
    return { 
     getName: getName 
    }; 
})(); 

如果你想使其可寫,你可以定義計算觀察到一個setter:

var getName = ko.computed({ 
    read: function() { 
     return customer().Name(); 
    }, 
    write: function(n) { 
     customer().Name(n); 
    } 
}); 

(不是最有意義的例子,但那是因爲你不真的需要一個在這裏計算的觀察值)