2013-03-01 63 views
1

我可能会错过一些非常简单的事情,但任何人都可以指出我在这里做错了吗?敲除无法解析绑定内部方法

非常感谢提前。

<div data-bind="foreach: agencies"> 
    <div data-bind="text:name"></div> 
    <div data-bind="text:email"></div> 
    <button data-bind="click: removeAgency">remove</button> 
</div> 

<script type="text/javascript"> 

    var agency = [{ 
     name : ko.observable('a'), 
     email : ko.observable('b') 
    }, { 
     name: ko.observable('c'), 
     email: ko.observable('d') 
    }]; 

    var vm = { 
     agencies: ko.observableArray(agency), 
     removeAgency: function(agency) { 
      this.agencies.remove(agency); 
     } 
    }; 

    ko.applyBindings(vm); 
</script> 

这是错误我得到:未捕获的错误:无法解析绑定。 消息:ReferenceError:removeAgency未定义; 绑定值:点击:removeAgency

回答

4

您绑定到该html中的代理,但您的方法在您的viewmodel上。试着这么做:

<button data-bind="click: $parent.removeAgency">remove</button> 

您可能需要重新JIG你的虚拟机,以获得范围正确:

var ViewModel = function(){ 
    var self = this; 
    self.agencies = ko.observableArray(agency), 
    self.removeAgency = function(agency) { 
     self.agencies.remove(agency); 
    } 
}; 

var vm = new ViewModel(); 

我仍然可以在作用域次迷茫,我不得不承认,但是给这试试看看会发生什么。

+0

没有类似的东西,但究竟这是你所需要的:) – 2013-03-01 10:48:42

+0

感谢快速回复@保罗。现在它说:不能调用方法'删除'未定义 – Iternity 2013-03-01 10:48:59

+0

好!谢谢@保罗。 – Iternity 2013-03-01 10:57:20

0

工作例如:

http://jsfiddle.net/marko4286/7RDc3/2034/ 

阅读文档http://knockoutjs.com/documentation/foreach-binding.html