0

我正在尝试确定一种基于鼠标事件显示或隐藏链接的方法。从 JSFiddle,我似乎无法让它工作。这是我到目前为止所拥有的:

HTML:

<ul multiple="multiple">  
    <!-- ko foreach: list -->   
    <li data-bind="event: {mouseover: $parent.showDelete, mouseout: $parent.hideDelete}">
        <div >
            <span style="vertical-align: center; height: 25px;" 
            data-bind="text: name"></span>
            <a data-bind="visible: $data.deleteVisible" href="#">Remove</a>
        </div>
    </li>        
    <!-- /ko -->
</ul>
<p>
    <button data-bind="click: addItem">Add</button>
    <button data-bind="click: removeItem">Remove</button>
</p>

JS:

$(function() {

    var data = [ {name: "Bob"}, {name: "Joe"}, {name: "John"} ]; 
    var viewModel = {
        list: ko.observableArray(data),
        deleteVisible: ko.observable(false), 
        addItem: function() {
            this.list.push({name: "Steve"});                       
        },
        removeItem: function() {
            this.list.pop();
        } ,        
        showDelete: function() {
            this.deleteVisible(true);
        },        
        hideDelete: function() {
            this.deleteVisible(false);
        }        
    };
    ko.applyBindings(viewModel);    
}); 

我知道绑定工作正常,因为数据显示并且链接被隐藏。但是,当我将鼠标悬停或鼠标移出时,我在控制台中收到以下错误:

Uncaught TypeError: Object #<Object> has no method 'deleteVisible' 
    viewModel.hideDelete
    (anonymous function)
    jQuery.event.dispatch
    elemData.handle

所以错误来自我的视图模型中的“hideDelete”。知道我做错了什么吗?

谢谢!

4

1 回答 1

0

您是否尝试过使用自我参考制作视图模型?

$(function() {

var data = [ {name: "Bob"}, {name: "Joe"}, {name: "John"} ]; 
function viewModel (){
    var self = this; 
    self.list = ko.observableArray(data);
    self.deleteVisible = ko.observable(false);
    self.addItem = function() {
        self.list.push({name: "Steve"});                       
    };
    self.removeItem = function() {
        self.list.pop();
    };        
    self.showDelete = function() {
        self.deleteVisible(true);
    };        
    self.hideDelete = function() {
        self.deleteVisible(false);
    };        
};
ko.applyBindings(viewModel);    

});

于 2013-04-18T20:54:12.873 回答