AmpersandJS / ampersand-view-switcher

A utility for swapping out views inside a container element.
MIT License
23 stars 13 forks source link

TypeError: Cannot read property 'empty' of undefined #35

Closed dhritzkiv closed 8 years ago

dhritzkiv commented 8 years ago

This TypeError halts everything and prevents views from switching.

Came across this issue after upgrading to ampersand-state@5.0.2 (the update which upgraded dependencies, including major bumps to lodash and ampersand-events).


Problem code (at L79):

ViewSwitcher.prototype._onViewRemove = function (view) {
    var emptyCb = this.config.empty; //<- the problem is here. - `config` is undefined. `this` doesn't refer to the ViewSwitcher instance, but the `view`.
   //...
};

which is triggered by (L74):

ViewSwitcher.prototype._registerRemoveListener = function (view) {
    if (view) view.once('remove', this._onViewRemove, this);
};

What's happening in _registerRemoveListener is view.once is being called with three arguments, the last two being the callback and the context. However, somewhere in the chain (I'm guessing ampersand-view -> ampersand-state -> ampersand-events) the third argument is no longer being correctly and the callback isn't being bound to this (the ViewSwitcher instance). Instead, it's being bound to view, which isn't right.

One solution is to change _registerRemoveListener to:

ViewSwitcher.prototype._registerRemoveListener = function (view) {
    if (view) view.once('remove', this._onViewRemove.bind(this)); // note the use of bind
};

I've tested it locally, and it fixes the issue.

I'm happy to file a PR with the change for this module, if all of this makes sense. Can someone review this issue, to make sure I'm not misdiagnosing this?


Edit: I removed some incorrect details from my diagnoses of the problem.