knockout.js文本更改取决于计数器

时间:2017-07-12 05:58:49

标签: javascript knockout.js

我是淘汰赛的新手,我希望文本更改值取决于计数器。可以使用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);
};

https://jsfiddle.net/launeric/b3929xcr/#&togetherjs=GkChVL86zO

2 个答案:

答案 0 :(得分:1)

首先,不要将计算出的定义放在增量函数中。您每次运行函数时都会重新定义计算结果,这会破坏计算的目的。

请记住,要从clickCount获取值,您需要调用它(一个observable是一个函数)。所以你的代码应该是这样的:

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

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

答案 1 :(得分:-1)

var viewModel = function() {
  this.name = ko.observable('Tabby');
  this.clickCount = ko.observable(0);
  this.catLevel = ko.observable('Newborn');
  this.imgSrc = ko.observable('https://static.pexels.com/photos/33358/cat-fold-view-grey-fur.jpg');
  this.imageAttribution = ko.observable('https://www.flickr.com/photos/onesharp/9648464288');
  this.incrementCounter = function() {
    this.clickCount(this.clickCount() + 1);
    if (this.clickCount() > 10) {
      console.log("brabra");
      this.catLevel("inFant");
    }
  };
}

ko.applyBindings(new viewModel());

http://jsbin.com/tiyijer/edit?html,css,js,console,output