Knockout not displaying when a value changes

落爺英雄遲暮 提交于 2019-12-13 19:25:28

问题


I am trying to use knockout to hide text if greater than a certain value. For some reason I cant get it to work. When I click the test button the second text field should show..

<body class="calc" onLoad="createnav()">
<input type="button" value="test" />

<p data-bind="text: 'This shows', if: 6 > 4" ></p>
<br>    
<p data-bind="text: 'This does Not', if: 6 > qty"></p>

Here is the script:

function AppViewModel() {
  this.qty = ko.observable("1"); } 
  // Activates knockout.js 
  var app = new AppViewModel(); ko.applyBindings(app);

//When I click button I want the name to change
$('input[type=button]').click( function() {
  var sum = '5';
  app.qty(sum);
});

http://jsfiddle.net/d577K/44/


回答1:


As others have pointed out, you're comparing the observable object qty instead of its value qty()

But you also might want to consider making your text a computed

Fiddle Example

<p data-bind="text: output"></p>

function AppViewModel() {
    var self = this;
    this.qty = ko.observable("1");
    this.output = ko.computed(function(){
        return (6 > self.qty()) ? "This shows too" : "";
    });
}

This is a more knockout-like way of doing things, and provides the advantage of keeping your logic inside your view model instead of mixing it in your markup.

Among other advantages of this, you would have been able to clearly see your javascript values when debugging, and notice that qty was a function rather than a number.

It also allows you to reuse this value without repeating the calculations if you want to show it in multiple places.




回答2:


You need to access the value of the qty observable:

<p data-bind="text: 'This does Not', if: 6 > qty()"></p>




回答3:


Simple,

<p data-bind="text: 'This does Not', if: 6 > qty()"></p>

You cannot use declarative binding (no parenthis) when observable property is used in expression



来源:https://stackoverflow.com/questions/15562239/knockout-not-displaying-when-a-value-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!