سؤال

I have the following code :

var profileToRemove = null;

//...

$("#buttonRemoveProfile").on("tap", {profile : profileToRemove}, removeProfile);

//...

function removeProfile(event){
   console.log(event.data);
   var profile = event.data.profil;
   if(profile==null || profile.name==null) {
      alert("Erreur lors de la suppression du profil");
   }
   else { /*remove profile*/ }
}

Before any tap on "#buttonRemoveProfile", "profileToRemove" is set to the desired value (not null!). Yet, my function removeProfile receives "null" (event.data is {profile : null}) or whatever the initial value of profileToRemove was.

So how can I pass the current value of removeProfile to my handler?

Thank you !

هل كانت مفيدة؟

المحلول 2

Change your design so that the data contains a function that returns what you want:

$("#buttonRemoveProfile").on("tap", {profile : function() {
        return profileToRemove;
    }
}, removeProfile);

function removeProfile(event){
   console.log(event.data);
   var profile = event.data.profile(); // Call the profile function
   if(profile==null || profile.name==null) {
      alert("Erreur lors de la suppression du profil");
   }
   else { /*remove profile*/ }
}

If you want to get fancy, you could allow the profile to be either a function or data, and use:

var profile = event.data.profile;
if (typeof profile == "function") {
    profile = profile();
}

نصائح أخرى

The data parameter in on() takes an object, and the value of that object is locked in at the time of binding, changing the profileToRemove variable later does not in any way update event.data.profile (which you typed incorrectly).

PROOF

As you already have a variable in a higher scope, it seems easier to use that directly

var profileToRemove = null;

$("#buttonRemoveProfile").on("tap", removeProfile);

//...

function removeProfile(){
   if( profileToRemove === null || profileToRemove.name === null) {
      alert("Erreur lors de la suppression du profil");
   } else { 
      /*remove profile*/ 
   }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top