tags:

views:

42

answers:

1

I have a component that fires an onFocus event. I am assigning a class method to handle the onFocus event. In the event handler I need access to both the class instance, and the event object itself.

However, when I use .bind(this), I can no longer get the event object because the scope is now changed to the class instance. And if I don't use .bind(this) I can access the event object, but not the class instance.

I'm sure there is a solution, but I have not been able to figure this out. Any ideas?

Thanks.

new Class( {
    handleComponentFocus : function() {
        // this refers to the class instance
        // I would also like to get the event information as well, but can't now that the scope has been changed    
    }.bind(this)

    this.pickList = new BasePickList( { 
        onFocus : this.handleComponentFocus
    });
})
+2  A: 

can you post more? basically - a skeleton for the class as well as the function where you call up a new instance of BasePickList. BasePickList source wouldn't hurt to see how the event is fired.

now, you don't need to do wrap the class method with a .bind(this), it does that automatically. as for events, depends on what fires them, if this is a input field then it ought to pass on the original event which you can capture via handleComponentFocus: function(e) { where e will be the event object.

this may be waaay off from what you are trying to do but it may give you some ideas http://www.jsfiddle.net/dimitar/KdhvG/

check console output when you focus on the field - it passes on control to the handleComponentFocus method with the event object (complete with event.target that points to the checkbox) as well as a scope of the class instance.

<input type="checkbox" id="foo" />

and

var banana = new Class({
    Implements: [Events, Options],
    initialize: function(options) {
        this.setOptions(options);
        this.element = document.id(this.options.element);
        this.element.addEvents({
            focus: function(e) {
                this.fireEvent("focus", e);
            }.bind(this)
        });
    }
});

var foo = new Class({
    handleComponentFocus: function(e) {
        console.log(e);
    },
    initialize: function() {
        this.picklist = new banana({
            element: "foo",
            onFocus: this.handleComponentFocus
        });
    }
});

new foo();
Dimitar Christoff