开发者

correct way to access class method in callback [prototype]

开发者 https://www.devze.com 2023-01-29 18:17 出处:网络
I\'m using prototype 1.7 and building a class that will essentially take a list of divs and builds a tab interface.

I'm using prototype 1.7 and building a class that will essentially take a list of divs and builds a tab interface.

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 t开发者_JAVA技巧o 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. When the callback runs, this.setCurrent(link) does nothing.

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. With Prototype you'll have to bind anonymous functions using bind(). After // init code do:

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. For details on binding see the Prototype API docs.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消