如何删除从 ajax 调用返回的 JSON 生成的 Knockout 映射数组的成员



我正在使用 knockoutjs 和映射插件从服务器调用返回的 JSON 生成视图模型。 我从服务器获取一个数组,创建一个将映射数组作为属性的模型,然后将数组数据绑定到模板以在屏幕上呈现所有数据。 效果很好。

我想在每个项目旁边渲染一个按钮,以便我将其删除,如本视频中的示例所示(请参阅大约 14:20)。

但是在视频中,他绑定到在数组元素上定义的函数。 我的元素是使用映射插件从 JSON 生成的,所以我不确定如何为每个元素添加一个函数,或者我什至想这样做。 或者,我是否可以将按钮的单击绑定到视图模型上的函数并传入与按钮关联的元素的 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>

这是模板:

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

和 HTML 以确保完整性:

<ul class="vertical" data-bind="template:{name:'supplierTemplate',foreach:suppliers}"></ul>

怎么样:

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

请参阅此处的注释 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 ); 
    }
};

最新更新