Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript de-anonymizing a click function

really basic stuff here. I'd like to give a click function a name and assign some parameters to it. The goal is code reusability such that I can write only one generic function for common tasks such as for enabling users to delete various data.

Here's a jsfiddle to show you what I mean.

And here's that code:

the HTML:

<button>delete this</button>
<div data-id="3" class="delete">something bad</div>
<div data-id="4" class="delete">something else bad</div>

and the JS:

// this function would be loaded on my site's template and therefore would be available across my entire site.
function deleteThis(data_id){           
   $('button').on('click', 'button', function(){
      $('div[data-id="'+data_id+'"]').hide();  
   });
}  

var clicked_id=3;
function deleteThis(clicked_id); 
// this function would be called on the various pages where users can delete things and this variable, clicked_id, would be assigned=3 by the user's action on that page.

How do I give this button click event a name?

update thanks all! the $('button') should have been $(document.body) or the button's parent element. It works if you make that simple change. You can also do it as Michael Buen suggests below.

like image 230
tim peterson Avatar asked Dec 02 '25 19:12

tim peterson


2 Answers

Just refactor your code, put the delete functionality on its own function

<button>delete this</button>
<div data-id="3" class="delete">something bad</div>
<div data-id="4" class="delete">something else bad</div>
​

$('button').on('click', function() { deleteImmediately(3) });

function deleteImmediately(id) { -- refactored code
    $('div[data-id='+id+']').hide();  
}​

Live test: http://jsfiddle.net/e2kuj/2/

like image 145
Michael Buen Avatar answered Dec 05 '25 10:12

Michael Buen


In your fiddler, the (function deleteThis(){})() is making it private and you are trying to access it as a global!

like image 38
epascarello Avatar answered Dec 05 '25 10:12

epascarello



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!