Nils Anders
Nils Anders

Reputation: 4410

Property is not defined

Im trying to understand the syntax of knockout and have running to problems.

Example of my ko viewmodel

var Market = function (e) {
    var self = this;
    self.MarketId = ko.observable(e ? e.MarketId : '');
    self.Description = ko.observable(e ? e.Description : '');
};

var MarketAddViewModel = function () {
    var self = this;
    var url = "/api/market";

    self.newMarket = ko.observable(new Market());

    // Save market
    saveMarket = function (item) {
        $.ajax({
            type: 'POST',
            url: url,
            data: ko.toJS(item),
            success: function (data) {
                // SUCCESS
            },
            error: function (err) {
                var err = JSON.parse(err.responseText);
                var errors = "";
                for (var key in err) {
                    if (err.hasOwnProperty(key)) {
                        errors += key.replace("employee.", "") + " : " + err[key];
                    }
                }

                alert('error');
                //$("<div></div>").html(errors).dialog({ modal: true, title: JSON.parse(err.responseText).Message, buttons: { "Ok": function () { $(this).dialog("close"); } } }).show();
            },
            complete: function () {
                // complete
            }
        });
    };
};

To bind it i use this code

 $(document).ready(function () {
            ko.applyBindings(new MarketAddViewModel());
        });

Then the HTML Element

<input data-bind="value: Description" type="text" class="required input-xxlarge" name="description" id="description" />

But when o load this page, i recieve "Description is not defined"

Any clue?

Upvotes: 0

Views: 127

Answers (2)

Anders
Anders

Reputation: 17554

You can use the with binding which will change the context for the child elements to the newMarket context

<div data-bind="with: newMarket">
    <input data-bind="value: Description" type="text" class="required input-xxlarge" name="description" id="description" />
</div>

edit: I can also take the opportunity to make some PR for my convention over configuration lib The above syntax would look like

<div data-name="newMarket">
    <input data-name="Description" type="text" class="required input-xxlarge" name="description" id="description" />
</div>

https://github.com/AndersMalmgren/Knockout.BindingConventions

Upvotes: 1

dan richardson
dan richardson

Reputation: 3939

I think it needs to be

<input data-bind="value: newMarket().Description" type="text" class="required input-xxlarge" name="description" id="description" />

(notice the newMarket().) as it's a property of the MarketAddViewModel instance. The parenthesis will extract the observable value so that its 'Description' attribute can be extracted.

Upvotes: 1

Related Questions