计算的可观察未定义

时间:2015-12-09 21:55:48

标签: 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 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());

1 个答案:

答案 0 :(得分:2)

您没有将Neighborhood函数的实例存储到Neighborhood可观察对象。尝试将代码更改为:

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})
);