VivekDev
VivekDev

Reputation: 25389

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

Upvotes: 0

Views: 7778

Answers (2)

Claudio Redi
Claudio Redi

Reputation: 68400

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>

Upvotes: 7

RodneyTrotter
RodneyTrotter

Reputation: 1166

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");
    };
    

Upvotes: 4

Related Questions