0

I'm using knockout.js and I want to have a Master ViewModel that contains multiple ViewModels. Then I want to print properties of the ViewModels to the user but I can not get it right. Please help.

JavaScript Code:

var aViewModel = function()
{
    self.test = "test from a";
};

var bViewModel = function()
{
    self.test = "test from b";
};

masterVM = {a: new aViewModel(),
            b: new bViewModel()};

ko.applyBindings(masterVM);

HTML Code:

<div id="test-div">
    <span data-bind="text: a.test"></span>
    <span data-bind="text: b.test"></span>
</div>

The fiddle address is: http://jsfiddle.net/ZyK4x/

Athanasios Emmanouilidis
  • 1,890
  • 3
  • 16
  • 24

1 Answers1

2

There isn't any magical self keyword in JavaScript.

It is only a common idiom which is used to maintain a reference to the this.

So you are missing the var self = this; from you view models:

var aViewModel = function()
{
    var self = this;
    self.test = "test from a";
};

var bViewModel = function()
{
    var self = this;
    self.test = "test from b";
};

Demo JSFiddle.

Community
  • 1
  • 1
nemesv
  • 133,215
  • 15
  • 395
  • 348