BAE
BAE

Reputation: 8936

why undefined error in the following backbone view codes?

const _ = require('underscore');

module.exports = (() => {
  const PANEL_HEADER_HEIGHT = 40;

  return Frame.extend({

  ...
    _handleSearch: _.debounce(ev => {
      if ( ev.keyCode !== 9 ) {
        const searchValue = $(ev.target).val();
        this.model.filterData(searchValue);
      }
    }, 1000),
   ...
})();

this.model.filterData(searchValue); converted to undefined.model.filterData(searchValue); in console.

Any idea?

Upvotes: 1

Views: 72

Answers (1)

Cory Danielson
Cory Danielson

Reputation: 14501

It seems to work if you re-write the method without using an arrow function.

https://jsfiddle.net/CoryDanielson/2dt30fhb/

var MyView = Backbone.View.extend({
    name: 'MY-VIEW',
    doStuff: _.debounce(function() {
        alert(this.name);
    }, 1000)
});

var view = new MyView();
view.doStuff();
// This will alert 'MY-VIEW'

The reason it's failing is because Babel will transpile the code to follow the ES6 spec.

module.exports = (() => {
  // this = undefined, because module.exports is global.
  return Frame.extend({
    // inherits this from above, undefined
    _handleArrowFunction: _.debounce(ev => {
      console.log(this);
    }),
    _handleRegularFunction: _.debounce(function() {
      console.log(this);
    })
  });
})

Look at the difference in how babel transpiles the code:

You can read more about arrow functions and the this value here:

Upvotes: 1

Related Questions