Bitten by the "this" scope issue in JavaScript callbacks

I took a step away from Angular and jQuery style coding conventions and dropped back to the traditional JS-style OOP, mainly because I wanted to get familiar with regular JS programming using the MDN docs, and learn the new HTML5 calls (which aren't new anymore).

I ended up coding using an MVC style, and consequently, added an event handling system. It was easy-but-cheesy so I eneded up using Backbone's event system. (It makes me look more hip.)

BTW, here's one way to use Backbone events within traditional JS code:

FooController = function() {
  var obj;
  function foo() {
    obj.trigger('myevent');
  }
  obj = {
    'foo': foo
  };
  _.extend(obj, Backbone.Events);
  return obj;
}

foofoo = new FooController();
foofoo.on('myevent', function () { ... });

Events and callbacks... the goto of contemporary programming. Your code only appears to be organized.

One thing I didn't realize was that Angular takes care of "this" for you. It says so in the docs, but it didn't hit home until I got bitten by the common gotcha (again): your callback calls a function, and that function uses "this", and when it's executed, "this" is bound to some other object.

This post discusses it in detail, and offers different solutions. This article is really good. Read it: What you should know about this

It's also hard to test. You won't write the unit test that would find this bug. You're not going to create the object, then add an event handler function that calls the method to be tested, then do something to trigger the event. You're not.

The tendency in Angular is to use "this". The habit in trad JS should be to avoid using "this". It creates public properties, which, in OOP, isn't a good habit anyway. Use var instead, and use local variables. Use getters and setters.

Now, I'm going to search my code for "this" and see if I can use local variables instead.