Sam*_*der 4 knockout-mapping-plugin knockout.js
我正在使用knockoutjs和映射插件从服务器调用返回的JSON生成视图模型.我从服务器获取一个数组,创建一个将映射数组作为属性的模型,然后数据将数组绑定到模板以呈现屏幕上的所有数据.哪个效果很好.
我希望每个项目旁边都有一个按钮,可以将其删除,就像在此视频中的示例一样(参见14:20左右).
但是在视频中,他绑定了一个在数组元素上定义的函数.我的元素是使用映射插件从JSON生成的,所以我不确定如何向每个元素添加一个函数,或者我是否想要这样做.或者,我可以单击按钮绑定到viewmodel上的函数并传入与该按钮关联的元素的id吗?
我的javascript:
<script type="text/javascript">
var supplierModel;
$(function(){
getAllSuppliers();
})
function getAllSuppliers(){
$.getJSON('/SWM60Assignment/allsuppliers',function(responseData){
supplierModel = new SupplierModel(responseData);
ko.applyBindings(supplierModel);
});
}
var SupplierModel = function (supplierList) {
var self = this;
self.suppliers = ko.mapping.fromJS(supplierList);
self.remove = function(supplierId){
// how can I get the buttons to call this method with the id
// of the element they are the button for?
alert('remove called with supplier id:'+supplierId);
}
};
</script>
Run Code Online (Sandbox Code Playgroud)
这是模板:
<script id="supplierTemplate" type="text/html">
<li>
Name: <span data-bind="text:name"></span> Address: <span data-bind="text:address"></span>
<button data-bind="click:<what can I put here to bind correctly>>">Remove supplier</button>
</li>
</script>
Run Code Online (Sandbox Code Playgroud)
和完整性的HTML:
<ul class="vertical" data-bind="template:{name:'supplierTemplate',foreach:suppliers}"></ul>
Run Code Online (Sandbox Code Playgroud)
eri*_*icb 10
怎么样:
<button data-bind="click: $parent.remove">Remove supplier</button>
Run Code Online (Sandbox Code Playgroud)
见这里的注1
如果你使用ko.mapping它说"阵列被转换成可观察的数组." 因此,您的suppliers属性将具有ko数组方法(如remove).
您也可能希望将实际内容传递supplier给您的remove函数:
var SupplierModel = function (supplierList) {
var self = this;
self.suppliers = ko.mapping.fromJS(supplierList);
self.remove = function(supplier){
// observable array
self.suppliers.remove( supplier );
}
};
Run Code Online (Sandbox Code Playgroud)