1

Currently trying to maintain an object approach, at the moment I want to call a toggle method when a click handler is actioned. So the handler is within the init method and when i click the link I call the toggle_pane() passing the link that's been click 'this', does this sound right or what should I be doing? All advice welcome!

Here is the snippet of code I'm working on:

JS

init: function(){

            var _ = this,
                slides_li = _.els.slides.children();

            // Click handlers
            slides_li.on('click', function(e) {
               _.toggle_pane(this); 
            });



        },
        toggle_pane: function(li){

            var _ = this,
                slides_li = _.els.slides.children();

            if( !$(li).hasClass('active')) {
             console.log( 'dont have active' );   
            }


        }            
styler
  • 13,569
  • 20
  • 73
  • 127
  • Possible duplicate. Check the link - http://stackoverflow.com/questions/337878/js-var-self-this – Sandeep G B Jun 12 '12 at 14:35
  • "this" shouldn't be passed as an argument, bind it to the function instead - _.toggle_pane.bind(this). Also as kevin said, the _ variable isn't the best naming convention – michael Jun 12 '12 at 14:40
  • hi, sorry what do you mean by binding to the function instead? – styler Jun 12 '12 at 14:47
  • something like this: slides_li.bind('click', _.toggle_pane.bind(this)); – styler Jun 12 '12 at 14:48
  • passing "this" as an argument is bad practice. you should be binding it like "_.toggle_pane.bind(this)" so that the "this" inside your toggle function has the correct scope – michael Jun 12 '12 at 14:52
  • thanks @michael, so is this correct slides_li.bind('click', _this.toggle_pane.bind(this)); – styler Jun 12 '12 at 14:56

1 Answers1

2

Yes, that is a way to do it. Although, a plain old underscore isn't the best variable name. I'd recommend something a little clearer, like var _this = this;.

Try looking around the jQuery source code itself, which does some juggling with this quite a bit.

kevin628
  • 3,342
  • 3
  • 23
  • 43