Mark C.
Mark C.

Reputation: 6460

Update Observable on View Model

I'm trying to allow the users to click a checkbox to toggle a boolean property, but I can't seem to be able to actually change the underlying View Model.

Model looks like:

var fund = function () {
        var self = this;

        self.Id = ko.observable();
        self.name = ko.observable();
        self.ticker = ko.observable();
        self.companyId = ko.observable();
        self.status = ko.observable();
        self.number = ko.observable();
        self.addedDate = ko.observable();
        self.comment = ko.observable();
        self.companyName = ko.observable();
        self.isSalary = ko.observable(); <-- 

The property at the bottom are the properties in question.. Here's my HTML.

<input type="checkbox" data-bind="checked: isSalary,  click: function(data) { $root.toggleReference(data, 'SAL', 'isSalary') }" />

And the function on my View Model..

toggleReference = function (currentFund, referenceAbbrev, updateProperty) {
        alert(currentFund.Id() + " "  + referenceAbbrev + " " + updateProperty);
}

I've tried applying bindings after this function finishes, and also :

var currentValue = currentFund[updateProperty];
fund.updateProperty = updateProperty;

They toggle the checkbox (because I'm clicking on it), when my alert comes through, but switches back to whatever state it was in when I initially applied the bindings when the function finishes. It's like although I am trying to update it, I am never reapplying the toggled value back to the view model.

How do I specifically update this property?

Note: On the HTML, I am using an observableArray() since we are dealing with things in a table format.

Upvotes: 0

Views: 45

Answers (2)

James Thorpe
James Thorpe

Reputation: 32222

Your click binding needs to return true, otherwise knockout is seeing it as an attempt to prevent the default behaviour. This should fix it:

<input type="checkbox" data-bind="checked: isSalary,  click: function(data) { $root.toggleReference(data, 'SAL', 'isSalary'); return true; }" />

Here's a simple fiddle demonstrating the issue.

Upvotes: 3

Brett Green
Brett Green

Reputation: 3765

The checked binding should handle the viewModel updates without any additional coding.

What's the click binding for? If you just want to inspect the state, debug on the backend with Chrome and see if the state is changing. The click may fire before the checked property is updated making you think it's not working.

Upvotes: 0

Related Questions