从内联计算方法引用observable

时间:2016-02-25 20:24:00

标签: knockout.js

我是否遗漏了任何内容,或者根本无法宣布计算出来的"内联"我的第一个例子中有id_and_name这样的属性?

function viewmodel(){

    var self = this;

    // adding 'inline' won't work (exception that the functions doesn't exist):
    self.person = ko.observable({
        id: ko.observable(),
        name: ko.observable(),
        id_and_name: ko.computed(function(){ return this.id() + this.name(); }, self.person)
    });

    // this works:
    self.person.id_and_name = ko.computed(function(){ 
        return this.id() + this.name(); 
    }, self.person);
}

1 个答案:

答案 0 :(得分:1)

好的,self.person未定义,直到 ko.observable调用返回后computed之前被引导,因此在self.person仍然是undefined时被引导。您可以在the computed source code file中查看,实际上很容易阅读。

这是一种看待它的方法:

function viewmodel() {
  var self = this;

  self.person = "temp";

  self.person = ko.observable({
    id: ko.observable(),
    name: ko.observable(),
    id_and_name: ko.computed(function() {
      console.log(this);
      return this.id() + this.name();
    }, self.person)
  });
}

初始化时会记录"temp",因为那时self.person 。创建后,您无法更改计算读取函数的this目标。

所以不,你想做什么是不可能做到的。您需要第二个解决方案或正确的视图模型构造函数*。

*您的顶级viewmodel已经是这样的构造函数。您可以使用personid属性创建内部构造函数name,然后new创建一个内部构造函数函数id_and_name,计算出的this将自动生成正确的E = zeros(1001,1001,l); %% using the number of loops as the last dimension for m=1:l %% Note: your for loop above only does one iteration; this makes it do `l` iterations (the letter L) xl=cos(2*pi*m*n/10000)'; yl=ex22_1(xl,g,a,b); %multiplication of matrix with its transpose resolves SUMn(yl[n])^2 z=yl*yl'; w=xl*xl'; E(:,:,m)=z/w; end /home/ec2-user/Enviziion/Muveoo/Server/node_modules/postcss/lib/lazy-result.js:157 this.processing = new Promise(function (resolve, reject) { ^ ReferenceError: Promise is not defined 绑定。