0

i have defined (saved) a function inside the .data() method of jQuery of an object, to use that function later on in my code.

Problem: how can i pass parameters to that function when i want to call (use) it.

ex:

// function declaration

var obj = {};
$(obj).data('callback',function(parameter[s]){
  // do something with parameter
});

// calling the function (usage)

$(obj).data('callback')(parameter[s]);
var obj = {};
$(obj).data('callback',function(number){
  console.log(number++);
});

$(obj).data('callback')(1);

is this that i have written right?

thank you for answering

2 Answers2

0

Do you want like this ?


var obj = {};
$(obj).data('callback',function(number){
    console.log(++number);
});
  
// calling the function (usage)
    
$(obj).data('callback')(1);

If you want pass array to parameters, you can use like this:

var obj = {};
$(obj).data('callback',function(parameter){
    console.log(parameter[3]);
});
  
// calling the function (usage)
    
let array = [1,2,3,4];
    
$(obj).data('callback')(array);


Or:

var obj = {};
$(obj).data('callback',function(parameter){
    console.log(parameter);
});
  
// calling the function (usage)
    
let array = [1,2,3,4];
    
$(obj).data('callback')(array[2]);


Osman Durdag
  • 955
  • 1
  • 7
  • 18
0

you did it correctly you must to change number++ to ++number and its better use arrow function same as follow:

$(obj).data('callback',(number)=>{
  console.log(number++);
});
Mehrzad Tejareh
  • 635
  • 5
  • 21
  • thanks mehrzad, can you please tell me why ++number and arrow functions is better to use – hossein1976 Sep 27 '20 at 10:07
  • `number++` solved your problem and arrow function is more popular feature in EF6 and i think this link is useful if my answer is useful for you; you makes me happy if you vote me [https://www.freecodecamp.org/news/when-and-why-you-should-use-es6-arrow-functions-and-when-you-shouldnt-3d851d7f0b26/] – Mehrzad Tejareh Sep 27 '20 at 10:17