Knockout not displaying when a value changes

2019-07-31 09:58发布

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/

3条回答
女痞
2楼-- · 2019-07-31 10:41

You need to access the value of the qty observable:

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

查看更多
我只想做你的唯一
3楼-- · 2019-07-31 10:42

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

查看更多
可以哭但决不认输i
4楼-- · 2019-07-31 10:49

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.

查看更多
登录 后发表回答