【问题标题】:Accessing Object variables in a callback在回调中访问对象变量
【发布时间】:2012-06-14 14:53:33
【问题描述】:

我有以下设计

function crudDataTable()
{
    this.addEditFormContainerSelector = ''; 
    this.paginationType = "full_numbers";  // Provide Pagination Type
    this.processing = true; 
    this.serverSide = true;  //I want this this to be accessible in fnRowCallback below:

    this.create = function(){

        this.tableInstance = $(this.tableLocationSelector).DataTable({
            "sPaginationType": this.paginationType
            fnRowCallback:function(nRow, aData) {
                // "this" from crudDataTable should be accessible here
            }  
        })
    }
}

我希望 crudDataTable 中的 this 可以在 fnRowCallback 中访问。

我怎样才能做到这一点?fnRowCallback 也是由datatable 组件触发的,所以这不在我的控制范围内。如何使 thisfnRowCallback 下可访问。

或者如果这是不可能的,那么还有什么其他方法可以实现它?

我正在尝试编写一个组件,这些组件的用户可以简单地设置其变量并调用 create 函数。我正面临在fnRowCallback 函数中访问this 的挑战。

谢谢。

【问题讨论】:

    标签: javascript callback scope


    【解决方案1】:

    您可以在回调之外存储对this 的引用:

    var table = this;
    this.tableInstance = $(this.tableLocationSelector).DataTable({
         "sPaginationType": this.paginationType,
         fnRowCallback: function(nRow, aData) {
             //Use `table` to refer to the instance of `crudDataTable`
         }  
    });
    

    或者,您可以使用 ES5 bind method(但请注意旧版浏览器不支持它):

    this.tableInstance = $(this.tableLocationSelector).DataTable({
         "sPaginationType": this.paginationType,
         fnRowCallback: function(nRow, aData) {
             //Use `this` to refer to the instance of `crudDataTable`
         }.bind(this);
    });
    

    【讨论】:

    • 这个var table 可以在 fnRowCallback 中访问吗?
    • 感谢您的出色回答并提供替代方案!
    • @linuxeasy - 没问题,很高兴我能帮上忙 :)
    猜你喜欢
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    • 2016-07-28
    • 2012-10-30
    • 1970-01-01
    相关资源
    最近更新 更多