如何将此传入jquery .change事件

时间:2018-03-02 23:26:31

标签: javascript jquery oop

我正在编写一个自定义的redactor插件,我需要将this传递给jquery .change事件。我怎样才能使以下工作?

(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);

1 个答案:

答案 0 :(得分:1)

在调用之前,只需将其值分配给另一个变量:

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

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

替代解决方案:

$('.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));

或者使用ES6 +的箭头功能(未经测试,应该可以使用):

$('.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);
});