简体   繁体   中英

knockout.js observable is not updating

Team,

I have a very simple html page with a viewmodel as follows.

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <script src='E:\Trials\ClientSide\MyTrials\knockout-2.2.1.js' type='text/javascript'></script>
    <script src='E:\Trials\ClientSide\MyTrials\jquery-2.0.0.js' type='text/javascript'></script>
    <title>Index</title>
    <script type="text/javascript">

        function PersonViewModel()
        {
            firstName = ko.observable("FirstN")
        };

        $(document).ready(function () {
            var person = new PersonViewModel();
            ko.applyBindings(person);
        });

    </script>
</head>
<body>
    <div>
        <h3>Details</h3>
        <p>First Name: <input data-bind="value:  firstName()" /></p>
        <p>First Name From span: <span data-bind="text: firstName()" ></span> </p>
    </div>
</body>
</html>

Its very simple and self explanatory. script block contains a view model, and on doc ready function, binding happens. And the html is also simple enough. One input and one span bound to same property firstName which is observable. But the pain is when I change the value from the input, the span does not update. What am I missing? Regards Vivek

Change firstName() to firstName

<p>First Name: <input data-bind="value:  firstName" /></p>
<p>First Name From span: <span data-bind="text: firstName" ></span> </p>

There are two problems here.

  1. As mentioned by Caludio, you are placing the brackets in your binding when it is not necessary. Refer to his answer for how to fix this.
  2. Your PersonViewModel is slightly wrong. You have forgotten to place the 'this.' in front of the firstName property. Fix it like so:

     function PersonViewModel() { this.firstName = ko.observable("FirstN"); }; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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