0

Please have few sec patience. js beginner. Thnx. I am playing with boilerplate https://github.com/jquery-boilerplate/jquery-boilerplate/blob/master/src/jquery.boilerplate.js

inside of it I added 2 new functions

   init: function () {

      this.mynewFunction2();
   },

    mynewFunction1: function (){

      console.log('ok');
    },

    mynewFunction2: function (){

       $('.link').click(function(){
             this.mynewFunction1();
       });
    }

you probably already see the problem but the question is how do I pass my mynewFunction1 to jquery object ? I did find few posts where they say that I need to assign my new function in order to be called inside jquery object but I am bit lost there. So if you have a spare minute could you please post an example based on my code above. Thank you!

2 Answers 2

2
 mynewFunction2: function (){
      var self = this;
       $('.link').click(function(){
             self.mynewFunction1();
       });
    }
Sign up to request clarification or add additional context in comments.

3 Comments

+1 because you're right, but would you care to explain to the OP why this works?
thnx nnnnn, yes a further insight would be great.
It is kinda like javascript automagically sets a new var this = ""context""; inside the function declaration, overriding the previous declaration. To understand this you must understand js variable scope first. It is not a 2 paragraph explanation; check this answer stackoverflow.com/questions/3127429/javascript-this-keyword
1

A new function creates a new scope, which in turn creates a new this:

mynewFunction2: function (){
   $('.link').click(function(){
         this.style.color = 'red';
         // this inside the event handler is the clicked element
   });
}

You can just drop the anonymous function and pass it directly:

mynewFunction2: function (){
   $('.link').click(this.mynewFunction1);
}

or if you have to pass parameters:

mynewFunction2: function (){
   var that = this; // references the parent object
   $('.link').click(function() {
      that.mynewFunction1(this); // passes the clicked element
   });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.