-1

I have a function that fires when I click on item inside my jquery datatable item.

$('.table tbody').on( 'click', '.item', function (e) {
   alert("clicked");
});

I have an item with the same class outside the datatable, that works with this function:

  $('.item').on( 'click', function (e) {
     alert("clicked");
  });

What is inside the function is for both the same. Is there a way to combine these two functions into one?

void
  • 36,090
  • 8
  • 62
  • 107
peace_love
  • 6,229
  • 11
  • 69
  • 157

1 Answers1

4

You can create a function first

const func = () => {
   alert("clicked")
};

and execute this inside both the event listeners

$('.table tbody').on( 'click', '.item', func);
$('.item').on( 'click', func);

Update:

And if you want the event inside the function then you can use arrow functions too.

const func = (e, el) => {
   e.preventDefault()
   alert($(el).attr("data-id"));
};

$('.table tbody').on( 'click', '.item', function(e){
     func(e, this);
});
$('.item').on( 'click',function(e){
     func(e, this);
});
void
  • 36,090
  • 8
  • 62
  • 107
  • why do I have to use `const func`? Why cannot I use `function clicked() { alert("clicked"); }` – peace_love Aug 16 '18 at 08:08
  • 1
    `const func` is a function expression in ES2015 JavaScript. You can write `function clicked() { alert("clicked"); }` this too and it will work just fine. – void Aug 16 '18 at 08:10
  • I need `function (e)` because I later have to use `e.preventDefault();` – peace_love Aug 16 '18 at 08:10
  • @Jarla you can do that too. See the updated answer :) It is a choice you need to make based on the syntactic you are following in your project. – void Aug 16 '18 at 08:12
  • Thank you, just wanted to learn, what does it mean to do it that way – peace_love Aug 16 '18 at 08:13
  • 1
    @Jarla glad to help. Read more here https://stackoverflow.com/questions/33040703/proper-use-of-const-for-defining-functions-in-javascript. Do mark it correct if it solves your problem. – void Aug 16 '18 at 08:13
  • 1
    Yes, I have to wait to more minutes until they let me mark it – peace_love Aug 16 '18 at 08:14
  • I tested it. I am using for example this variable in my function `var id = $(this).attr("data-id");` and now with your function if `alert(id)` the output is `undefined` – peace_love Aug 16 '18 at 08:18
  • You need to pass this as an argument and in the function fetch the data attribute using this passed param. – void Aug 16 '18 at 08:19
  • like this `const func = (e, id) => {`and `$('.edit-item').on( 'click', func(id));`? – peace_love Aug 16 '18 at 08:25
  • yes, ok, just never worked with thi const func. So I was confused. Thank you for help! – peace_love Aug 16 '18 at 08:30