明确地将计算机订阅到可观察量

时间:2018-02-21 14:46:49

标签: javascript knockout.js

在以下代码中,有没有办法明确订阅compb,以便点击change a然后点击change b将始终触发comp (无论在change a之前点击change b多少次?

[请注意,我不是在寻找一个解决方案,比如从self.b()块(或其他类似的技巧)中取出else,而是明确调用某些函数,我想这类似的东西到subscribe]

var ViewModel = function () {
  var self = this;
  self.a = ko.observable(true);
  self.b = ko.observable(1);
  self.changeA = function () {
      console.log("changeA clicked");
      self.a(!self.a());
  }
  self.changeB = function () {
      console.log("changeB clicked");
      self.b(0);
  }

  self.comp = ko.computed(function () {
      if (!self.a()) {
          console.log("a");
          // ... some code that computes a ... 
      }
      else {
          console.log("b");
          var b = self.b();
          // ... some code that computes b ... 
      }
      return "hello";
  })
}
vm = new ViewModel();
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<button data-bind="click: changeA, text: 'change a'"></button>
<button data-bind="click: changeB, text: 'change b'"></button>

2 个答案:

答案 0 :(得分:0)

使用订阅者和其他可观察者是否有任何问题?

$item['price'] = 0;
/*code to get item information goes in here*/
if((string)$item['price'] == 'e') {
    $item['price'] = -1;
}
var ViewModel = function() {
  var self = this;
  self.a = ko.observable(true);
  self.b = ko.observable(1);

  self.changeA = function() {
    self.a(!self.a());
  }
  self.changeB = function() {
    self.b(0);
  }

  self.comp = ko.observable();

  self.b.subscribe(function(newVal) {
    console.log('b was changed to ', newVal);
    self.comp(newVal);
  })
}
vm = new ViewModel();
ko.applyBindings(vm);

答案 1 :(得分:0)

@Roy J在他的评论中是正确的:给定的代码是尝试以错误的方式做某事的好兆头。我会把这个问题留作警告标志。

相关问题