基本上我在 JS 中有以下代码片段:
var pgViewModel = {
inited : false,
username : ko.observable("", {persist: "login.username"}),
password : ko.observable("", {persist: "login.password"}),
vehicles : ko.observableArray(),
selectedVehicle : ko.observable(null, {persist: "login.vehicle"}),
tirepressure : ko.computed(function(){
var selecV = this.selectedVehicle();
return selecV.tirepressure_vl + '/' + selecV.tirepressure_vr + '/' + selecV.tirepressure_hl + '/' + slecV.tirepressure_hr + 'bar';
},this),
在尝试加载页面时,我收到错误:“this.selectedVehicle() 不是函数”。出现这个问题是因为函数解析时pgViewModel还没有准备好?有没有可能的解决办法。抱歉,我不明白这里的问题的每一个细节。谢谢。
最佳答案
您遇到的问题与调用时的上下文和 this
值有关。强烈建议避免在knockout
View 模型中直接使用this
。相反,创建额外的 self
字段将在对象创建时初始化。
var self = this;
...
tirepressure : ko.computed(function(){
var selecV = self.selectedVehicle();
似乎您的 ViewModel
搞砸了一些东西,没有完整的代码,无法找到根本原因。我对其进行了一些更新,一切似乎都工作正常:
function pgViewModel() {
var self = this;
self.inited = false;
self.username = ko.observable("", {persist: "login.username"});
self.password = ko.observable("", {persist: "login.password"});
self.vehicles = ko.observableArray();
self.selectedVehicle = ko.observable(null, { persist: "login.vehicle"});
self.tirepressure = ko.computed(function() {
var selecV = self.selectedVehicle();
return selecV.tirepressure_vl + '/' + selecV.tirepressure_vr + '/' + selecV.tirepressure_hl + '/' + slecV.tirepressure_hr + 'bar';
}, self);
};
ko.applyBindings(new pgViewModel());
关于javascript - KnockoutJs 计算 - 'Is not a function',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21523745/