Javascript 计算可观测未定义
地址总是以未定义的形式出现Javascript 计算可观测未定义,javascript,knockout.js,Javascript,Knockout.js,地址总是以未定义的形式出现 var Neighborhood = function(data){ this.street = ko.observable(data.street); this.city = ko.observable(data.city); this.address = ko.computed(function(){ return this.street + ' ' + this.city; },this); } var V
var Neighborhood = function(data){
this.street = ko.observable(data.street);
this.city = ko.observable(data.city);
this.address = ko.computed(function(){
return this.street + ' ' + this.city;
},this);
}
var ViewModel = function(){
var streetStr = 'aaa';
var cityStr = 'ccc';
console.log('street 1 - var: ' + streetStr);
// Initialize Neighborhood object with data from the given address
self.Neighborhood = ko.observable({
street: streetStr,
city: cityStr});
console.log('Obj street : ' + this.Neighborhood().street);
console.log('Obj address : ' + this.Neighborhood().address);
};
ko.applyBindings(new ViewModel());
您没有将
邻域
函数的实例存储到可观察的邻域。尝试将代码更改为:
var Neighborhood = function(data){
this.street = ko.observable(data.street);
this.city = ko.observable(data.city);
this.address = ko.computed(function(){
return this.street() + ' ' + this.city();
});
};
self.Neighborhood = ko.observable(new Neighborhood({
street: streetStr,
city: cityStr})
);
如果您能展示更多信息/您尝试的解决方案/分享您的研究,我们将不胜感激。您的帖子目前有点简洁,看起来像是一篇“为我调试此代码”的帖子。请注意,在堆栈溢出时,您可以随时编辑帖子以改进/增强它们。