Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete member of Knockout mapped array generated from JSON returned from ajax call?

I'm using knockoutjs and the mapping plugin to generate view models from JSON returned from a server call. I get an array from the server, create a model which has the mapped array as a property, then data bind the array to a template to render all of the data on screen. Which works great.

I'd like to have a button rendered next to each item which would allow me to remove it, like in the example in this video (see about 14:20).

But in the video he binds to a function defined on the elements of the array. My elements are generated from the JSON using the mapping plugin, so I'm not sure how I add a function to each element, or if I even want to do that. Or can I make the click of the button bind to a function on the viewmodel and pass in the id of the element the button is associated with?

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

and this is the template:

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

and the HTML for completeness:

<ul class="vertical" data-bind="template:{name:'supplierTemplate',foreach:suppliers}"></ul>
like image 753
Sam Holder Avatar asked Dec 27 '22 02:12

Sam Holder


1 Answers

how about:

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

see Note 1 here

If you use ko.mapping it says that "Arrays are converted into observable arrays." So, your suppliers property will have the ko array methods ( like remove ) on it.

You also might want to pass in the actual supplier to your remove function as well:

var SupplierModel = function (supplierList) {
    var self = this;

    self.suppliers = ko.mapping.fromJS(supplierList);
    self.remove = function(supplier){
        // observable array
        self.suppliers.remove( supplier ); 
    }
};
like image 93
ericb Avatar answered Jan 31 '23 01:01

ericb