15

我有一种感觉,我在这里错过了一些简单的东西,但就是不能完全理解这一点。这是我的脚本:

function FormDefinition()
{
    var self = this;
    self.Fields = ko.observableArray([new FieldDefinition()]);    
}

function FieldDefinition()
{
    var self = this;
    self.Name = "Test";
}
function ViewModel()
{
    var self = this;
    self.formDef = ko.observable(new FormDefinition());
    self.Name = "bob"
    self.addField = function(){
        this.formDef().Fields().push(new FieldDefinition());                    
    }            
}

ko.applyBindings(new ViewModel());

这是我的标记:

<a data-bind="click: addField">Add</a><br/>
<span data-bind="text: Name"></span>
<ul data-bind="foreach: formDef().Fields">
    <li data-bind="text: Name"></li>
</ul>​

这是一个 jsFiddle:http: //jsfiddle.net/5xSmr/

预期的行为是单击“添加”会导致 ui 更新。调试显示 addfield 被调用。

4

2 回答 2

30

修复了你的小提琴:http: //jsfiddle.net/5xSmr/2/

<a data-bind="click: AddField">Add</a><br/>
<span data-bind="text: Name"></span>
<ul data-bind="foreach: formDef().Fields()">
    <li data-bind="text: Name"></li>
</ul>
function FormDefinition()
{
    var self = this;
    self.Fields = ko.observableArray();    
}

function FieldDefinition()
{
    var self = this;
    self.Name = "Test";
}
function ViewModel()
{
    var self = this;
    self.formDef = ko.observable(new FormDefinition());
    self.Name = "bob"
    self.AddField = function(){
        this.formDef().Fields.push({Name:"test"});
    }            
}

ko.applyBindings(new ViewModel());

主要问题是您正在调用 Fields() 而不仅仅是 Fields。Fields() 返回解包后的数组,并通过直接推送到它,ko 永远不会知道它。

于 2012-04-27T20:58:17.887 回答
3

干得好 :-)

http://jsfiddle.net/JasonMore/Q6J6a/3/

看法

<a href='#' data-bind="click: AddField">Add</a><br/>
<span data-bind="text: Name"></span>
<ul data-bind="foreach: formDef.Fields">
    <li data-bind="text: Name"></li>
</ul>​

Javascript

var FormDefinition = function ()
{
    var self = this;
    self.Fields = ko.observableArray();    
}

var ViewModel = function()
{
    var self = this;
    self.formDef = new FormDefinition();
    self.Name = ko.observable("bob");
    self.AddField = function(){
        self.formDef.Fields.push({Name:"test"});            
    }            
}

ko.applyBindings(new ViewModel());

​</p>

​</p>

于 2012-04-27T20:58:08.447 回答