kristjan reinhold
kristjan reinhold

Reputation: 2048

Jquery messes up "this" in Ember

Im trying to delete a specific ember formset. Normally in my controller, This reffers to the controller , but after jquery script this = "p"aragraph.

Template

<p {{bind-attr class=id}}{{action 'getId'}}> Delete</p>

Javascript

 getId: function(){
       $( "p" ).on('click',function() {
         var Id = $( this ).attr('class');
         console.log(Id); // Returns id properly . 
         // here this reffers to "p" normally it reffers to the controller.
       });
        this.deleteSpecificFormset(Id); // "Id" is now undefined
       },

   deleteSpecificFormset: function(formCounterID){
      var oldPersonFormCount = this.get('personFormCount'); // This as json containing e.g {id:1}
      var newFormCounter = oldPersonFormCount[formCounterID -1].delete;
      this.set('personFormCount', newFormCounter);
    },

You can ofc offer ember related versions to that

cheers,

Kristjan

Upvotes: 0

Views: 90

Answers (1)

max
max

Reputation: 6069

It looks like a function scoping issue. Try defining Id in the outer function, it is later available in that same context.

 getId: function(){
       var Id; //declare the variable outside of the context of the jQuery anonymous function scope
       $( "p" ).on('click',function() {
         Id = $( this ).attr('class');
         console.log(Id); // Returns id properly . 
         // here this reffers to "p" normally it reffers to the controller.
       )};
        this.deleteSpecificFormset(Id); // "Id" should now be defined
 }

Alternatively, you can hold the outer scope this reference in a self variable and call deleteSpecificFormset from inside the callback:

getId: function(){
           var self = this;
           $( "p" ).on('click',function() {
             var Id = $( this ).attr('class');
             self.deleteSpecificFormset(Id);
           )};

     }

Upvotes: 1

Related Questions