我可能错过了一些非常简单的东西,但有人能指出我在这里做错了吗?
提前感谢。
<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>
这是我得到的错误:Uncaught错误:无法解析绑定。消息:ReferenceError: removeagent未定义;绑定值:click: removeAgency
你在那个html中绑定了一个代理,但是你的方法在你的视图模型上。试试这样写:
<button data-bind="click: $parent.removeAgency">remove</button>
您可能需要重新调整vm以获得正确的作用域:
var ViewModel = function(){
var self = this;
self.agencies = ko.observableArray(agency),
self.removeAgency = function(agency) {
self.agencies.remove(agency);
}
};
var vm = new ViewModel();
我不得不承认,我有时仍然会对作用域感到困惑,但请尝试一下,看看会发生什么。
工作示例:
http://jsfiddle.net/marko4286/7RDc3/2034/
阅读文档http://knockoutjs.com/documentation/foreach-binding.html