0

I'm working on an MVVM web app using Knockout.js, require.js etc. The problem is that I can't access items within a property (of type observable array) in my viewmodel.

Sample contract model:

define('model.contract', ['ko'],
    function (ko) {
        var Contract = function () {
            var self = this;
            self.id = ko.observable();
            self.subject = ko.observable().extend({ required: true });

            self.shoppingItems = ko.observableArray();

           };
           return Contract;
    });

Sample view model:

define('vm.contract', ['ko'],
    function (ko) {
        var contract = ko.observable(), // Is initialised as viewmodel activates

            deleteCmd = function () {

                var selectedId = getSelectedId(),
                    deletedId = contract.shoppingItems.remove(function (item) { return item.id === selectedId; });

                alert('Item ' + deletedId[0].id + ' was deleted!');
            };

        return {
            contract: contract,
            deleteCmd: deleteCmd
        };
    });

Sample view:

<div data-bind="template: {name: shoppingItemTemplate, foreach: contract().shoppingItems}"></div>
<button data-bind="click: deleteCmd">Delete Selected</button>

All I need to access in viewmodel is contract.shoppingItems and all I get is undefined.

Suresh Kamrushi
  • 15,627
  • 13
  • 75
  • 90
Pejman
  • 3,784
  • 4
  • 24
  • 33

1 Answers1

0

Why have you defined your contract as observableArray rather than just observable?

Also do not forget that you should call contract() to get value of contract observable:

// ...
deletedId = contract().shoppingItems.remove(function (item) { return item.id === selectedId; });
// ...

Update: Just noticed that you improperly defined model.contract. Place your return Contract outside of Contract definition block :)

define('model.contract', ['ko'],
    function (ko) {
        var Contract = function () {
            var self = this;
            self.id = ko.observable();
            self.subject = ko.observable().extend({ required: true });

            self.shoppingItems = ko.observableArray();
         };

        return Contract;
    }
);
Brigand
  • 84,529
  • 20
  • 165
  • 173
Rango
  • 3,877
  • 2
  • 22
  • 32
  • Sorry that was a mistake. I corrected it. And you're right about the `contract()` but the problem persists. – Pejman Mar 16 '13 at 10:29
  • Well, this is awkward, but this problem only existed here not in my original code. I corrected here too. Actually my model works fine and that's why my bindings for `shoppingItems` list work. – Pejman Mar 16 '13 at 10:44