【问题标题】:How to delete member of Knockout mapped array generated from JSON returned from ajax call?如何删除从 ajax 调用返回的 JSON 生成的 Knockout 映射数组的成员?
【发布时间】:2012-05-01 12:30:54
【问题描述】:

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

我想在每个项目旁边呈现一个按钮,以便我将其删除,就像this video 中的示例一样(见大约 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>

【问题讨论】:

    标签: knockout.js knockout-mapping-plugin


    【解决方案1】:

    怎么样:

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

    见注 1 here

    如果你使用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 ); 
        }
    };
    

    【讨论】:

    • 谢谢!我知道这一定是可能的,只是不确定语法是什么。
    • 删除项目后,供应商对象的长度不会改变。任何方式都可以。
    • 应该的。你如何查询这个数组的长度?
    猜你喜欢
    • 2014-01-26
    • 2019-12-12
    • 2019-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-20
    • 1970-01-01
    相关资源
    最近更新 更多