2012-06-18 29 views
1

我在JCarousel控件的顶部添加了一些功能。由于它在我们代码中的很多地方都有使用,所以我开始为它创建一个JQuery Widget。我的问题是,我无法在JCarousel控件的回调方法中获得对“this”对象的引用。请参阅下面的示例代码以供参考。如何在我的自定义JQuery Widget回调中访问'this'

(function ($, undefined) { 
$.widget('custom.MyCarousel', { 
    options: { 
     noOfVisibleItems: 2 
     }, 
    _init: function() { this.BindCarosuel(); }, 
    BindCarosuel: function() { 
    jQuery(this.element).jcarousel({ 
     size: this.options.noOfVisibleItems.length, 
     itemLoadCallback: { this.mycarousel_itemLoadCallback } 

     }); 
    }, 
    MyWidgetCustomMethod: function (index) { 
    }, 
    mycarousel_itemLoadCallback: function (carousel, state) { 
     // How to get access to options object (noOfVisibleItems) 
     // and methods like MyWidgetCustomMethod ? 
    } 
    } 
) 
} (jQuery)); 

我的问题是方法mycarousel_itemLoadCallback内 - 如代码上面提到,如何获得访问“这个”小部件实例?我尝试使用$ .custom.MyCarousel.prototype对象,但是这会为不同的窗口小部件实例返回相同的选项数据。

在此先感谢。

+0

如果您不介意这个问题,固定缩进?现在的方式确实很难遵循。 –

回答

-1

试试这个:

$(this)[0] 
or 
this[0] 

我不知道这是否会用这个插件可以工作,但作为一个经验法则 - 当你有一个jQuery实例的回调中,你想访问底层对象,那么你可以使用数组操作符来访问它,正如我在上面给你展示的那样。

+0

以上两个选项都给出错误:$(this)[0] .options未定义,并且此[0]未定义。 –

+0

'console.log(this)'和'console.log($(this))'在开发者控制台中显示的是什么? –

+0

这有类型'DispHTMLWindow2',所以是$(this)[0]。猜测都是指引发回调的对象。但我想要小部件实例。 –

0

最简单的解决方案是使用me'hack'。通过将this分配给变量me在更全局的私有范围内,这意味着您可以访问回调中的对象。尝试像这样:

(function ($, undefined) 
{ 
    $.widget('custom.MyCarousel', 
    { 
     me: this, 

     options: { 
      noOfVisibleItems: 2 
     }, 

     _init: function() { this.BindCarosuel(); }, 

     BindCarosuel: function() 
     { 
      jQuery(this.element).jcarousel({ 
       size: this.options.noOfVisibleItems.length, 
       itemLoadCallback: { this.mycarousel_itemLoadCallback } 

      }); 
     }, 

     MyWidgetCustomMethod: function (index) { 

     }, 

     mycarousel_itemLoadCallback: function (carousel, state) { 
      // How to get access to options object (noOfVisibleItems) 
      // and methods like MyWidgetCustomMethod ? 

      alert(me.options.noOfVisibileItems); 
     } 
    }) 
}(jQuery)); 
+2

我试过这种方法,但代码给出了错误:'我'是未定义的。 –

+1

所以你一定错过了'我:这个,顶部 –

2

我想我找到了解决我的问题:使用$ .proxy。感谢大家的帮助。因此,修改后的路线是:

itemLoadCallback: { $.proxy(Self.mycarousel_itemLoadCallback, this) } 

然后在回调方法,这将启动指的是小部件实例。

+0

所以'自我'只是有'this'分配给它,在jcarousel电话之前呢? –

+0

这是一个社区网站,你可以问,但你不贡献? –

-1

我认为以下解决方案的工作

jQuery(this.element).jcarousel({ 
    size: this.options.noOfVisibleItems.length, 
    itemLoadCallback: function(){ return this.mycarousel_itemLoadCallback() } 

    }); 
相关问题