Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a KnockoutJS template binding with jQuery UI confirmation dialog

How would I go about using a jQuery UI dialog to confirm whether they want to delete a row from a a list within a KnockoutJS template?

As I see it, the Knockout demos show a template which renders each row in a grid. The delete button calls the viewModel.remove() function passing in the object of the row to delete. Inside the remove() function, this.Gifts.Remove() is called with the data passed into the function as a parameter.

My problem is that I want to display a jQuery dialog to ask for confirmation of whether a row should be deleted. JQuery dialog works on the basis of a setup function which sets up the dialog and its delete function beforehand.

When I click on my delete link in the template, it opens the dialog ok, but how do I pass the template data into the dialog delete function, as it is now completely decoupled from the template mechanism?

like image 403
jaffa Avatar asked Apr 07 '11 16:04

jaffa


1 Answers

I am assuming that the dialog is from jQuery UI. If so, then you your remove would look something like this:

removeItem: function(item) {
    $( "#dialog-confirm" ).dialog({
        resizable: false,
        height:140,
        modal: true,
        buttons: {
            "Delete item": function() {
                $(this).dialog("close");
                viewModel.items.remove(item);
            },
            Cancel: function() {
                $(this).dialog("close");
            }
        }
    });
}

So, the "Delete item" button would close the dialog and also remove your item from your observableArray.

Working sample here: http://jsfiddle.net/rniemeyer/CLxsV/

Edit: better sample using bindings here: http://jsfiddle.net/rniemeyer/WpnTU/

like image 163
RP Niemeyer Avatar answered Sep 17 '22 16:09

RP Niemeyer