简体   繁体   English

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

[英]How to correct bind properties with ko.computed (Knockout.js)

I use Knockout.js and I face with this problem. 我使用Knockout.js,遇到了这个问题。 The problem is property "newString" view incorrect data on page: "no image". 问题是属性“ newString”在页面“ no image”上查看不正确的数据。 I want to see another string: "image1". 我想查看另一个字符串:“ image1”。 Help me to fix this problem. 帮助我解决此问题。

 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); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> <p data-bind="text: newString"></p> 

The first problem here is that you can't use this on object literals, you have to use function declaration . 这里的第一个问题是您不能在对象文字上使用this ,而必须使用函数声明 Also, you can't access observable values directly, you have to "call" them like this : 另外,您不能直接访问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> 

Otherwise, if you want to stay with object literal, you can declare your computed outside the object declaration : 否则,如果您想保留对象文字,则可以在对象声明之外声明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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM