如何使用ko.computed(Knockout.js)更正绑定属性

时间:2018-02-19 16:49:32

标签: javascript knockout.js

我使用Knockout.js,我遇到了这个问题。问题是属性" newString"在页面上查看不正确的数据:"没有图像"。我想看另一个字符串:" image1"。帮我解决这个问题。



Case
When (columnA,ColumnB,ColumnC,..,ColumnZ) = 'Something' Then 'Yes'
Else No
End

var viewModel = {
  new_property_first: ko.observable('image1'),
  new_property_second: ko.observable('image2'),

  newString: ko.computed(function() {
    if (this.new_property_first == 'image1') {
      return 'image1';
    } else if (this.new_property_second == 'image2') {
      return 'image2';
    } else {
      return 'no_image';
    }
  }, this),
};

ko.applyBindings(viewModel);




1 个答案:

答案 0 :(得分:1)

这里的第一个问题是你不能在对象文字上使用this,你必须使用function declaration。此外,您无法直接访问observable值,您必须“呼叫”,如下所示:

function ViewModel() {
  this.new_property_first = ko.observable('image1');
  this.new_property_second = ko.observable('image2');
  
  this.newString = ko.computed(function() {
    if (this.new_property_first() == 'image1') {
      return 'image1';
    } else if (this.new_property_second() == 'image2') {
      return 'image2';
    } else {
      return 'no_image';
    }
  }, this);
}

ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<p data-bind="text: newString"></p>

否则,如果你想留在对象文字中,你可以在对象声明之外声明你的computed

var viewModel = {
  new_property_first: ko.observable('image1'),
  new_property_second: ko.observable('image2')
}

viewModel.newString = ko.computed(function() {
  if (this.new_property_first() == 'image1') {
    return 'image1';
  } else if (this.new_property_second() == 'image2') {
    return 'image2';
  } else {
    return 'no_image';
  }
}, viewModel)

ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<p data-bind="text: newString"></p>