为什么这个knockoutjs observableArray不会导致UI更新?

问题描述 投票:13回答:2

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

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被调用。

javascript knockout.js
2个回答
23
投票

修正了你的小提琴: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永远不会知道它。


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());

© www.soinside.com 2019 - 2024. All rights reserved.