0

So, I have this:

function foo(){

  var that = this;

  this.elements = [
    $bar = $('.bar'),
    $foo = $('.foo')
  ];

  this.example = function(){
    alert("a");
  }

  this.elements.$bar.on('click', that.example);
}

and it's not working, however if I change this line:

  this.elements.$bar.on('click', that.example);

for this one:

  this.elements.$bar.on('click', function(){ that.example() });

That is, wrapping the method into an anonymous function, it does work...

EDIT: It also works if the method is not within the constructor function..

1 Answer 1

1

I think there's nothing wrong with how you attach your method in your current code. Though I notice that you've called your DOM Element like this:

this.elements = [
    $bar = $('.bar'),
    $foo = $('.foo')
];

this.elements.$bar

Instead, try to assign them as an object:

this.elements = {
    $bar : $('.bar'),
    $foo : $('.foo')
 };

Then in your code:

this.elements.$bar.on('click', that.example);

Here's a sample jsfiddle for further details: http://jsfiddle.net/b1bsc1rd/

Hope this helps for you

Sign up to request clarification or add additional context in comments.

1 Comment

Oh, I figured it out, the event attachment has to be after the method, otherwise it's undefined and jQuery ignores it and doesn't throw any error, if you want, edit your answer so this can be useful to others that in the future may have the same question.

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.