Reputation: 409
When I try to get the value of foo.Id in the click event (removeAFoo -> removeFoo) in the I get function text 'function b(){if(0...'. What needs to change to get the property value of foo.Id? Another weird thing is when I call indexOf() on viewModel.foos array it returns the index even though that array says it's zero length.
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>
http://jsfiddle.net/suedeuno/gAUgV/12/
Upvotes: 1
Views: 3508
Reputation: 3239
To get the value of foo.id you need to remember to use parentheses:
like so:
document.write(foo.Id());
Upvotes: 6