当我尝试在单击事件(removeAFoo -> removeFoo)中获取 foo.Id 的值时,我得到函数文本'function b(){if(0...'。需要更改什么来获取属性值foo.Id? 另一个奇怪的事情是,当我在 viewModel.foos 数组上调用 indexOf() 时,它会返回索引,即使该数组说它的长度为零。
function getFoos() {
viewModel.foos([]);
var data = [{
Id: 1,
Name: 'Joe' },
{
Id: 2,
Name: 'Jon' },
{
Id: 3,
Name: 'Jim' }
]
for (var i = 0; i < data.length; i++) {
var f = new foo();
f.Id(data[i].Id);
f.Name(data[i].Name);
viewModel.foos.push(f);
}
};
var viewModel = {
foos: ko.observableArray([]),
reloadFoos: function() {
getFoos();
},
removeAFoo: function(foo) {
removeFoo(foo);
}
};
var foo = function() {
this.Id = ko.observable();
this.Name = ko.observable();
};
function removeFoo(foo) {
alert(viewModel.foos.indexOf(foo));
alert(foo.Id);
viewModel.foos.splice(viewModel.foos.indexOf(foo), 1);
}
ko.applyBindings(viewModel);
getFoos();
<div data-bind="foreach: foos">
<div style="float: left">
<button data-bind="click : $parent.removeAFoo, attr: { id: Id }">
</button>
<label data-bind="text: Name">
</label>
</div>
</div>