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!

Benn
  • 4,840
  • 8
  • 65
  • 106

2 Answers2

2
 mynewFunction2: function (){
      var self = this;
       $('.link').click(function(){
             self.mynewFunction1();
       });
    }
enapupe
  • 15,691
  • 3
  • 29
  • 45
  • 2
    +1 because you're right, but would you care to explain to the OP why this works? – nnnnnn Sep 21 '13 at 14:27
  • thnx nnnnn, yes a further insight would be great. – Benn Sep 21 '13 at 14:28
  • 1
    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 http://stackoverflow.com/questions/3127429/javascript-this-keyword – enapupe Sep 21 '13 at 14:31
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
   });
}
adeneo
  • 312,895
  • 29
  • 395
  • 388