回调这个上下文 [英] Callback this context

查看:145
本文介绍了回调这个上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

in App:

  var bootstrap = new Bootstrap 
bootstrap.init(this,this.onBootstrapComplete);



在Bootstrap中:

  this.init = function(app,completeHandler){
_app = app;
_completeHandler = completeHandler;
...
}

...

var _allReady = function(){
_completeHandler(_app);
}

返回应用程式:

  this.onBootstrapComplete = function(app)
{
app.something();
app.someValue = ...
}

strong> this 上下文内的onBootstrapComplete。
它工作,但它不正确:)



如果让我们说我想直接从应用程序调用onBootstrapComplete,我会调用它< > 。



我可以这样做,所以我的onBootstrapComplete看起来像这样:

  this.onBootstrapComplete = function()
{
this.something();
this.someValue = ...
}


解决方案

我建议使用underscore.js。有关详情,请参见 http://underscorejs.org/#bind

  this.onBootstrapComplete = _.bind(function(){
...
this.someFunction(); //此上下文现在可用
...
},this);


in App:

var bootstrap = new Bootstrap();
bootstrap.init( this, this.onBootstrapComplete );

in Bootstrap:

this.init = function( app, completeHandler ){
    _app = app;
    _completeHandler = completeHandler;
        ...
}

...

var _allReady = function(){
        _completeHandler( _app );
}

back in App:

this.onBootstrapComplete = function( app )
{
        app.something();
        app.someValue = ...
}

I wanted to get this context inside onBootstrapComplete. It works but it doesn't look right :)

If let's say I wanted to call onBootstrapComplete directly from App, I would have to call it this.onBootstrapComplete( this ).

How can I do it so my onBootstrapComplete looks like this:

this.onBootstrapComplete = function()
{
        this.something();
        this.someValue = ...
}

解决方案

I would recommend using underscore.js. See http://underscorejs.org/#bind for further information.

this.onBootstrapComplete = _.bind( function() {
   ...
   this.someFunction(); // this context is available now
   ... 
}, this );

这篇关于回调这个上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆