Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/422.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript js文本更改取决于计数器_Javascript_Knockout.js - Fatal编程技术网

Javascript js文本更改取决于计数器

Javascript js文本更改取决于计数器,javascript,knockout.js,Javascript,Knockout.js,我是一个新手,我喜欢有一个文本更改值取决于计数器。可以使用observable或我需要订阅来完成吗? 我正在学习udacity js设计模式课程,但尚未涵盖订阅 但当我在谷歌上搜索类似的解决方案时,它使用了订阅 谢谢你的帮助 <h3 data-bind="text: catLevel"></h2> <div data-bind="text: clickCount"></div> this.incrementCounter = fu

我是一个新手,我喜欢有一个文本更改值取决于计数器。可以使用observable或我需要订阅来完成吗? 我正在学习udacity js设计模式课程,但尚未涵盖订阅 但当我在谷歌上搜索类似的解决方案时,它使用了订阅 谢谢你的帮助

    <h3 data-bind="text: catLevel"></h2>
    <div data-bind="text: clickCount"></div>

this.incrementCounter = function(){
    this.clickCount(this.clickCount()+1);
    //if (this.ClickCount > 10){
    //this.catLevel='Infant';
    //}

      this.catLevel = ko.computed(function() {
        if(this.clickCount>10){
          return "Infant";
        }else{

          return "Newborn";
        }
    //return this.firstName() + " " + this.lastName();
}, this);
};

this.incrementCounter=函数(){
this.clickCount(this.clickCount()+1);
//如果(此项。单击计数>10){
//这个.catLevel='baby';
//}
this.catLevel=ko.computed(函数(){
如果(此项。单击计数>10){
返回“婴儿”;
}否则{
返回“新生儿”;
}
//返回此.firstName()+“”+此.lastName();
},这个);
};


首先,不要将计算出的定义放入增量函数中。每次函数运行时都会重新定义computed,这违背了computed的目的

请记住,要从
clickCount
中获取值,您需要调用它(可观察对象是一个函数)。因此,您的代码应该如下所示:

  this.catLevel = ko.computed(function () {
    if (this.clickCount() > 10) {
      return "Infant";
    } else {
      return "Newborn";
    }
  }, this);

  this.incrementCounter = function () {
    this.clickCount(this.clickCount() + 1);
  };
  this.catLevel = ko.computed(function () {
    if (this.clickCount() > 10) {
      return "Infant";
    } else {
      return "Newborn";
    }
  }, this);

  this.incrementCounter = function () {
    this.clickCount(this.clickCount() + 1);
  };