0

I'm writing a custom redactor plugin and I need to pass in this into a jquery .change event. How can I get the following to work?

(function($R)
{
    $R.add('plugin', 'customplugin', {
        onmodal: {
            image: {
                open: function($modal, $form)
                {
                    this._load($modal)
                }
            }
        },
        _load: function($modal)
        {
            var $body = $modal.getBody();
            this.$box = $R.dom('<div>');

            this._getData('hello world'); //This works

            $('.item').change(function (this) { //'this' passed in here
                var value = $(this).val();

                this._getFoo(value); //This does not work

                return false;
            }).keyup(function () {
                $(this).change();
            });
        },
        _getFoo: function(param) {
            console.log('_getFoo() called with param ' + param);
        },
    });
})(Redactor);
Nadine
  • 777
  • 1
  • 11
  • 24

1 Answers1

1

Simply assign its value to another variable before calling it:

var that = this;  // You can rename to what `this` represents here

$('.item').change(function() {
  // Use `that` here, e.g.:
  that._getFoo(value);
});

Alternative solution:

$('.item').change(function(e) {
  // Use `e.currentTarget` when you'd use `this` here before
  var value = $(e.currentTarget).val();

  // Use `this` to access parent scope's `this`, e.g.:
  this._getFoo(value);
}.bind(this));

Or using ES6+'s arrow functions (untested, should work):

$('.item').change(e => {
  // Use `e.currentTarget` when you'd use `this` here before
  var value = $(e.currentTarget).val();

  // Use `this` to access parent scope's `this`, e.g.:
  this._getFoo(value);
});
Jeto
  • 14,596
  • 2
  • 32
  • 46