我在这样的对象中定义了我的函数:
i have my functions defined in an object like this:
_clickHandler: function(event){ event.preventDefault(); }, attachClickEv: function(element){ ...... element.on('click', this._clickHandler); },问题是我似乎无法将this传递给clickHandler函数
the problem is that I cannot seem to pass "this" to the clickHandler function
我知道我可以将其包装在另一个函数中,例如
I know that I could wrap that in another function like
var tthis = this; element.on('click', function(event){ tthis._clickHandler(event, tthis); });但后来我不能用
element.off('click', this._clickHandler);还有其他办法吗?
推荐答案您可以使用bind。这是一个例子:
You can use bind for that. Here is an example:
element.on('click', this._clickHandler.bind(this)); //later in the code... _clickHandler: function(event) { }既然你正在使用jQuery,你也可以使用 jQuery.proxy()太。更多信息: api.jquery/jQuery.proxy
Since you're using jQuery though, you can also use jQuery.proxy() too. More here: api.jquery/jQuery.proxy
更新:
要访问回调中的元素,您必须使用 event.target 或 event.currentTarget 或执行以下操作(取决于您正在做什么 ):
To get access to the element inside the callback you would have to use event.target or event.currentTarget or do the following (depends on what you're doing):
element.on('click', this._clickHandler.bind(this, element)); //later in the code... _clickHandler: function(element, event) { }另一种方法是将元素设置为对象的属性,如: this.element = $(' #el')然后在你的回调中使用它。
Another way is to set the element as a property of the object like: this.element = $('#el') and then use that in your callback(s).
实例: jsbin/mezuberucu/1/edit?html,js,output
更多推荐
将其他参数传递给事件处理程序
发布评论