Knockout.js - 多个ViewModel不起作用

时间:2014-07-07 10:08:55

标签: knockout.js

我正在使用knockout.js,我希望拥有一个包含多个ViewModel的Master ViewModel。然后我想打印ViewModels的属性给用户,但我无法正确。请帮忙。

JavaScript代码:

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代码:

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

小提琴地址是: http://jsfiddle.net/ZyK4x/

1 个答案:

答案 0 :(得分:2)

JavaScript中没有任何神奇的self关键字。

只有common idiom which is used to maintain a reference to the this.

所以你错过了查看模型中的var self = this;

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

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

演示JSFiddle