【发布时间】:2014-05-13 04:31:00
【问题描述】:
我正在使用具有诸如添加新行,删除新行之类的功能的应用程序。所有的东西都工作正常。就像我第一次从项目中加载数据(我有很多视图模型绑定在单个页面),所有数据似乎都按预期工作(无论何时编辑值,在我的视图模型中更新)。但是当我第二次加载现有数据时,视图模型没有按预期更新。即使我编辑了数据,视图模型也持有相同的数据。我认为 observable 无法正常工作。请告诉我到底在哪里做错了。
第一次:
function ViewModel() {
var self = this;
//Available types - which will come from serverside
self.typeDropDown = ko.observableArray(InitialData);
self.typeValue = ko.observable();
//Explicitly Adding new Row
self.Inputs = ko.observableArray([new Item(self.typeDropDown[0], '', '', '')]);
self.removeRow = function (Item) {
self.Inputs.remove(Item);
},
self.addNewRow = function () {
//push will add a new element to the container without modifying much in DOM
self.Inputs.push(new Item(self.typeDropDown[0], '', '', ''));
}
function Item(Type, StrData, MaxData, Back) {
var self = this;
self.Type = ko.observable(Type),
self.Storage = ko.observable(StrData),
self.MaxIOPS = ko.observable(MaxData),
self.BackupPercentagePerMonth = ko.observable(Back)
}
第二次 - 从服务器加载数据。
来自服务器的示例输入结构:
strJSON = [
{
Type: storageInitialData[0].Value,
Str: '12',
Max: '156',
Back: '123'
},
{
Type: storageInitialData[0].Value,
Str: '12',
Max: '156',
Back: '123'
}, {
Type: storageInitialData[0].Value,
Str: '12',
Max: '156',
Back: '123'
}
];
function ViewModel() {
var self = this;
//Available types - which will come from serverside
self.typeDropDown = ko.observableArray(InitialData);
self.typeValue = ko.observable();
//Explicitly Adding new Row
self.Inputs = ko.observableArray(strJSON);
self.removeRow = function (Item) {
self.Inputs.remove(Item);
},
self.addNewRow = function () {
//push will add a new element to the container without modifying much in DOM
self.Inputs.push(new Item(self.typeDropDown[0], '', '', ''));
}
ko.observableArray(strJSON) 是否不足以为数组中的元素设置可观察属性?我需要再次调用 Item 方法吗?
更新
我的下拉菜单是这样的
<select class="ddText" id="selType" style="width: 100px"
data-bind="options:typeDropDown, optionsText: 'Value', optionsValue: 'Value',value : (Type.Value)?Type.Value : Type,attr: { name: 'str',id : 'strType_'+$index()}, uniqueName:true" ">
</select>
【问题讨论】:
标签: knockout.js observable knockout-mvc