简体   繁体   English

在回调[prototype]中访问类方法的正确方法

[英]correct way to access class method in callback [prototype]

I'm using prototype 1.7 and building a class that will essentially take a list of divs and builds a tab interface. 我正在使用原型1.7,并构建一个类,该类实际上将采用div列表并构建一个tab界面。

var tabs = Class.create({
    initialize: function(container, options) {
        this.options = Object.extend({
            // additional options
            tabsRendered: null,
        }, options || {});

        // init code

        if( this.options.tabsRendered ) {
            this.options.tabsRendered();
        }
    },

    // additional methods

    setCurrent: function(link){
        //adds a .current class to tab clicked and its corresponding section
    }
};

new vtabs( 'products', {
    tabsRendered: function(){
        if( window.location.hash != "" ) {
            var link = $$( 'a[href$="' + window.location.hash + '"]');
            this.setCurrent(link);
        } 
    }
});

My question relates to my tabsRendered custom callback. 我的问题与我的tabsRendered自定义回调有关。 When the callback runs, this.setCurrent(link) does nothing. 当回调运行时, this.setCurrent(link)不执行任何操作。

If I pass this into the callback, my custom callback works as expected. 如果我进入回调这一点 ,因为我的预期回调的定制作品。

if( this.options.tabsRendered ) {
    this.options.tabsRendered(this);
}

My guess is that passing this into the callback is not best practice. 我的猜测是,通过进入回调是不是最好的做法。 So, how would I allow access to a method from within a callback? 那么,我如何允许从回调中访问方法?

Thanks 谢谢

The problem is that tabsRendered is unbound . 问题是tabsRendered未绑定的 With Prototype you'll have to bind anonymous functions using bind() . 使用Prototype,您必须使用bind()绑定匿名函数。 After // init code do: // init code执行:

if (Object.isFunction(this.options.tabsRendered))
  this.options.tabsRendered = this.options.tabsRendered.bind(this);

After that you can call this.options.tabsRendered() and within that once-anonymous function, this will refer to the right object. 之后你可以调用this.options.tabsRendered()并在那个曾经匿名的函数中, this将引用正确的对象。 For details on binding see the Prototype API docs . 有关绑定的详细信息,请参阅Prototype API文档

EDIT: As commented: it's correct that anonymous functions aren't the only ones affected. 编辑:正如评论:正确的是,匿名函数不是唯一受影响的函数。 It's the this from the scope from which a function was defined. 这是this从已定义的功能范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM