I have a knockout viewModel with an array of items. I want to watch one property (selected) on all the items and take action when it's changed.
For that I have a SectionManager that will do that. I initialize the manager and set up subscribes for every item. The myid
closure is not captured, it is always 3
, the last value. Can somebody tell me where I've lost it?
Example: If you click on an item in the list, the asterisk will indicate if it is selected. That works. The subscribed function is called too, and the myid
is written to the console, but that's always 3
.
John
HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="Scripts/jquery-1.7.2.js"></script>
<script type="text/javascript" src="Scripts/knockout-2.1.0.debug.js"></script>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<ul data-bind="foreach: roles">
<li data-bind="click: toggle">
<span data-bind="text: id"></span>
<span data-bind="visible: selected">*</span>
</li>
</ul>
</body>
</html>
and this script:
var roles = [
{ id: 1 },
{ id: 2, selected: true },
{ id: 3 }
];
var viewModel = (function (roles) {
var obj = {};
var arr = [];
for (var i = 0; i < roles.length; i++) {
arr.push({
id: roles[i].id,
selected: ko.observable(roles[i].selected || false),
toggle: function () {
this.selected(!this.selected());
}
});
}
obj.roles = ko.observable(arr);
return obj;
})(roles);
var sectionManager=(function(){
return {
init: function (roles) {
for (var i = 0; i < roles.length; i++) {
var item = roles[i];
var myid = item.id;
item.selected.subscribe(function () {
console.log(myid); // ALWAYS 3!!
});
}
}
};
})();
$(function () {
sectionManager.init(viewModel.roles());
ko.applyBindings(viewModel);
});