如何在我的自定义JQuery Widget回调中访问“this”

时间:2012-06-18 07:53:55

标签: jquery jquery-plugins widget

我在JCarousel控件之上添加了一些功能。由于它在我们的代码中的许多地方使用,所以我开始为它创建一个JQuery Widget。我的问题是我无法在JCarousel控件的回调方法中获得对“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中 - 如上面的代码所述,如何访问'this'小部件实例?我尝试使用$ .custom.MyCarousel.prototype对象,但这会为不同的小部件实例返回相同的选项数据。

提前致谢。

4 个答案:

答案 0 :(得分:2)

我想我找到了我的问题的解决方案:使用$ .proxy。谢谢大家的帮助。所以修改的行是:

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

然后在回调方法中,这将开始引用小部件实例。

答案 1 :(得分: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)

试试这个:

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

我不确定它是否适用于这个插件,但是根据经验 - 当你在回调中有一个jquery实例,并且你想访问底层对象时,你可以使用数组操作符来访问正如我在上面向你展示的那样。

答案 3 :(得分:-1)

我认为以下解决方案有效

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

    });
相关问题