Reputation: 1799
Basically I want visible:
to fire up only on the div i hover over, but it applies to all of them,
no matter which one I hover over.
I guess that makes sense, since I am binding to visible:
inside foreach:
loop, so it is applied to all of them. Is there a KnockoutJS work-around, or should I just use $jQuery.hover()
to make it work instead?
Html:
<div>
<div data-bind="foreach: hostGroups">
<div data-bind="css: { style: true }, event: { mouseover: $root.showDeleteLink, mouseout: $root.hideDeleteLink }">
<span data-bind="text: hostName"></span>
<span class="delete-link" data-bind="visible: $root.deleteLinkVisible">this is a delete link</span>
</div>
</div>
</div>
JavaScript:
var data = [
{ "hostName": "server1" },
{ "hostName": "server2" },
{ "hostName": "server3" }
];
var viewModel = {
hostGroups: ko.observableArray(data),
deleteLinkVisible: ko.observable(false),
showDeleteLink: function() {
viewModel.deleteLinkVisible(true);
},
hideDeleteLink: function() {
viewModel.deleteLinkVisible(false);
}
};
ko.applyBindings(viewModel);
http://jsfiddle.net/pruchai/KXtTU/3/
Upvotes: 4
Views: 3358
Reputation: 5813
showDeleteLink and hideDeleteLink in the jsfiddle you posted are throwing JavaScript errors.
Here's the fix: http://jsfiddle.net/KXtTU/1/
Updated JS:
var data = [
{ "hostName": "server1" },
{ "hostName": "server2" },
{ "hostName": "server3" }
];
var viewModel = {
hostGroups: ko.observableArray(data),
deleteLinkVisible: ko.observable(false),
showDeleteLink: function() {
viewModel.deleteLinkVisible(true); // added "viewModel."
},
hideDeleteLink: function() {
viewModel.deleteLinkVisible(false); // added "viewModel."
}
};
ko.applyBindings(viewModel);
Upvotes: 1
Reputation: 126052
You should implement hiding and showing the link on each individual item instead of on the root view model. For example:
JavaScript:
var data = [
{
"hostName": "server1"},
{
"hostName": "server2"},
{
"hostName": "server3"}
];
function Item(hostName) {
var self = this;
this.hostName = ko.observable(hostName);
this.deleteLinkVisible = ko.observable(false);
this.showDeleteLink = function() {
self.deleteLinkVisible(true);
};
this.hideDeleteLink = function() {
self.deleteLinkVisible(false);
};
}
function ViewModel() {
var self = this;
this.hostGroups = ko.observableArray(ko.utils.arrayMap(data, function(item) {
var newItem = new Item(item.hostName);
return newItem;
}));
}
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
Html:
<div>
<div data-bind="foreach: hostGroups">
<div data-bind="css: { style: true }, event: { mouseover: showDeleteLink, mouseout: hideDeleteLink }">
<span data-bind="text: hostName"></span>
<span class="delete-link" data-bind="visible: deleteLinkVisible">this is a delete link</span>
</div>
</div>
</div>
Example: http://jsfiddle.net/KXtTU/4/
Upvotes: 2