4

基本上我只想visible:在我悬停的 div 上启动,但它适用于所有这些,无论我悬停在哪一个上。

我想这是有道理的,因为我绑定到visible:内部foreach:循环,所以它适用于所有循环。是否有 KnockoutJS 解决方法,或者我应该使用$jQuery.hover()它来代替它?

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/

4

2 回答 2

2

您应该在每个单独的项目上而不是在根视图模型上实现隐藏和显示链接。例如:

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>​

示例:http: //jsfiddle.net/KXtTU/4/

于 2012-10-05T21:47:09.010 回答
1

您发布的 jsfiddle 中的 showDeleteLink 和 hideDeleteLink 正在引发 JavaScript 错误。

这是修复:http: //jsfiddle.net/KXtTU/1/

更新的 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);
于 2012-10-05T21:41:30.140 回答