McDonnellDean
McDonnellDean

Reputation: 1087

What is wrong with my binding?

Before we start I would like to point out that this is day zero using html / js and knockout so I may just have misunderstood how it all works together.

I have made a simple test webapi so I can get to grips with knockout. It is all working so far but for the binding <span data-bind="text:currentMember().name"></span> which I cannot seem to get to work.

The Page

<!DOCTYPE html>
<html>
<head>
    <title>Test page</title>
    <script src="Scripts/knockout-2.2.1.js"></script>
    <script src="Scripts/jquery-2.0.0.js"></script>
    <script src="Scripts/ViewModels/indexViewModel.js" defer="defer"></script>
</head>
<body>
    <div id="Content">
        <section>
            <p>Member Number: </p>  <input id="memberNumber" type="text" />
            <p>Pin: </p>  <input id="memberPin" type="text" />
            <input type="submit" value="Get" data-bind="click: getMember" />
        </section>
        <span data-bind="text:currentMember().name"></span>
    </div>
</body>
</html>

The ViewModel

function IndexViewModel() {
var self = this;

self.currentMember = ko.observable();

self.getMember = function () {

    var memberNumber = $('#memberId').val();
    var memberPin = $('#memberPin').val();

    if (memberNumber == '' || memberPin == '') {
        memberNumber = '372-001100-134';
        memberPin = '123456';
    }

    $.ajax({
        dataType: "json",
        url: "http://localhost:25979/api/members/GetMemberByNumberAndPin",
        data: {
            memberNumber: memberNumber,
            pin: memberPin
        },
        success: function (serviceResponse) {
            if (!serviceResponse.hasAlerts) {
                self.currentMember(serviceResponse.body);
                alert(self.currentMember().name);
            }
        }
    });
};
}

ko.applyBindings(new IndexViewModel());

EDIT: I have changed the code and now the alert does indeed work but the html binding is still not updating.

Upvotes: 1

Views: 74

Answers (1)

NilsH
NilsH

Reputation: 13821

You have declared currentMember as an observable. And to set the value of an observable, you need to invoke it as a function. So try self.currentMember(serviceResponse.body) instead. If you do self.currentMember = seviceResponse.body as you do, you will essentially re-define the currentMember variable as a regular non-observable variable.

Check the documentation for further explanation.

Upvotes: 5

Related Questions