user1400995
user1400995

Reputation:

Knockout binding issue with razor syntax

I'm new to Knockout and I'm trying to bind for example the 'first' variable so that it initialises and displayed properly during vm construction:

@Html.EditorFor(model => model.first, new { htmlAttributes = new { @class = "form-control", data_bind = "value:first" } })

and in my script section I declare the following:

var ViewModel = function (data) {
        var self = this;
        self.first = ko.observable(data.first);
        self.second = ko.observable(data.second);

        self.third = ko.computed(function () {
            return  Number(this.first()) + Number(this.second());
        });
    };

    var data = { first: '1000', second: '1000' };
    ko.applyBindings(new ViewModel(data));

Obviously I'm somewhere wrong, but dont know where.

Update: The rendered page:

<input class="form-control text-box single-line" data-bind="value:first" data-val="true" data-val-number="my text" data-val-range="Please contact us" data-val-range-max="150000" data-val-range-min="5000" id="first" name="first" type="text" value="" />

Upvotes: 0

Views: 179

Answers (1)

James Thorpe
James Thorpe

Reputation: 32222

The issue you've got here is that your computed is trying to make use of first and second, but the value of this will be wrong in that context. This means when knockout tries to evaluate the function, it will error, breaking the rest of the page.

The quickest fix, since you're already using self is to just use that within the computed:

self.third = ko.computed(function () {
    return  Number(self.first()) + Number(self.second());
});

An alternative fix is to make the value of this what you want, which can be achieved by using bind:

self.third = ko.computed(function () {
    return  Number(this.first()) + Number(this.second());
}.bind(this));

You'll see some of the knockout computed examples use this second form.

Upvotes: 1

Related Questions