【问题标题】:How to pass an argument of parent method to it's inner calling methods?如何将父方法的参数传递给它的内部调用方法?
【发布时间】:2013-09-30 07:04:16
【问题描述】:

我正在尝试调用file uploader 插件。选择文件时,将从库中调用add 方法。在调用add 时,我需要以add 方法作为参数传递父方法参数opts

这是一段使用 RequireJS 库的代码。

 return {            
        onFileChoose: function (e, data) {
            // I need 'opts' object here
        },
        start: function (opts) {
            $('fileupload').fileupload({
                url: '//testbucket.s3.amazonaws.com', // Grabs form's action src
                type: 'POST',
                autoUpload: true,
                dataType: 'xml', 
                add: this.onFileChoose
            });
        }
 }

我需要onFileChoose 中的opts 对象。

我试过了

add: function (e, data) {
    this.onFileChoose(e, data, opts);
}

上面的代码产生了this.onFileChoose is undefined的错误。

如何解决这个问题?

【问题讨论】:

    标签: javascript jquery scope this jquery-file-upload


    【解决方案1】:

    问题出在回调方法内部,this 没有引用具有方法的对象

    使用闭包变量

    return {            
        onFileChoose: function (e, data) {
            // I need 'opts' object here
        },
        start: function (opts) {
            var self = this;
            $('fileupload').fileupload({
                url: '//testbucket.s3.amazonaws.com', // Grabs form's action src
                type: 'POST',
                autoUpload: true,
                dataType: 'xml', 
                add: function (e, data) {
                    self.onFileChoose(e, data, opts);
                }
            });
        }
    }
    

    或使用 $.proxy()

    return {
        onFileChoose: function (e, data) {
            // I need 'opts' object here
        },
        start: function (opts) {
            $('fileupload').fileupload({
                url: '//testbucket.s3.amazonaws.com', // Grabs form's action src
                type: 'POST',
                autoUpload: true,
                dataType: 'xml',
                add: $.proxy(function (e, data) {
                    this.onFileChoose(e, data, opts);
                }, this)
            });
        }
    }
    

    【讨论】:

    • 谢谢,效果很好。如果我在 start 方法中声明 this.options = opts。我可以像$.proxy(this.onFileChoose, this) 一样添加它吗?这样this.options 就可以在this.onFileChoose 方法中访问。
    • 你能告诉我为什么它不是最佳选择吗?
    • @JustinJohn 我会选择 opt #2
    猜你喜欢
    • 2019-02-27
    • 2012-02-23
    • 1970-01-01
    • 2011-07-18
    • 1970-01-01
    • 2011-05-01
    • 2011-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多