Dmitry S
Dmitry S

Reputation: 33

pass variables from one event handler to another in javascript

I have the following js code in the view:

//here I initialize two variables to temporaly store values
var id = 0;
var tr = "";

$(document).on("click", ".deleteItem", function(e) {
        $('#deleteItemConfirmationModal .modal-body').html("Please confirm deleting this item");
        $('#deleteItemConfirmationModal').modal('show');   
        // here I need two parameters (id and tr) to pass them into another function, so I save them into variables      
        id = $(this).data('id');
        tr = $(this).closest("tr");
    });

Then if a user confirms the item should be deleted. The code for this as follows:

$('#deleteItemConfirmationModal .modal-footer').on('click', function(event) {
    var $button = $(event.target);
    buttonId = $button[0].id;

    if (buttonId === 'yesBtn') {
        $.ajax({
            url: '@Url.Action("Delete")',
            type: 'POST',
            data: { itemId: id },  // use first variable
            success: function (data) {
                if (data.IsOK) {
                    tr.remove();    // use second variable
                }
            }
        });
    }
});

The code works fine. But i don't think that it's a good practice to pass variables like this.

Can I use this approach or there is another one without using global variables?

Upvotes: 1

Views: 2244

Answers (2)

Sagiv b.g
Sagiv b.g

Reputation: 31024

You can trigger custom events and pass data to them.
Here is a simple example:

$('#root').on('click', '#one, #two',function(e){
  $('#root').trigger('myEvent', {param: e.target.id})
});

$('#root').on('myEvent',function(e,data){
  console.log(data.param);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<div id="root">
  <div id="one" class="btn btn-info">one</div>
  <div id="two" class="btn btn-info">two</div>
</div>

Upvotes: 1

Chris Lear
Chris Lear

Reputation: 6742

You could attach the variables to the modal. Something like

$('#deleteItemConfirmationModal').data('id', id);
$('#deleteItemConfirmationModal').data('tr', tr);

Then when you want to use them, just fetch the values back

var id = $('#deleteItemConfirmationModal').data('id');
var tr = $('#deleteItemConfirmationModal').data('tr');

That should be safe, because the values apply to the modal while it's showing. Effectively, you're attaching them to the document, and I can see why you have a bit of unease.

Upvotes: 2

Related Questions