jQuery / javascript事件 - 原型事件处理程序 [英] jQuery/javascript events - prototype event handler

查看:117
本文介绍了jQuery / javascript事件 - 原型事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码不能正常工作,因为我直观地期望它:

  function MyObject(input){
input.change(this._foo);
this.X = undefined;
}

MyObject.prototype._foo = function(){
alert(This code does never called);
//但如果它
this.X = true;
}

var test_input = $(input#xyz); // a random,existing input

var m = MyObject(test_input); // attach handler(或try to)

test_input.change(); // trigger event

alert(m.X); // undefined



我希望 _foo()将被调用(如果发生这种情况, _foo()中的



有没有人知道为什么这不工作,以及将对象传递给事件处理程序的任何替代模式?

$ b

解决方案 你还需要确保 this c> _foo 是指 MyObject 实例

一种方法: -

  function MyObject(input){
var _this = this;
input.change(function(){
//将_foo中的`this`显式设置为`_this`
_this._foo.call(_this);
});
this.X = undefined;
}

MyObject.prototype._foo = function(event){
alert(This is called);
//和'this',为'm',X设置为true
this.X = true;
//文本框必须由'event.target'访问,而不是'this'如果你需要它
}

var test_input = jQuery(input#xyz); // a random,existing input

var m = new MyObject(test_input); // attach handler(或try to)

test_input.change(); // trigger event

alert(m.X); // true

PS
你不能避免使用new操作符! :)


The following code doesn't work as I intuitively expect it to:

function MyObject(input) {
   input.change(this._foo);
   this.X = undefined;
}

MyObject.prototype._foo = function() {
   alert("This code is never called");
   // but if it did
   this.X = true;
}

var test_input = $("input#xyz"); // a random, existing input

var m = MyObject(test_input); // attach handler (or try to)

test_input.change(); // trigger event

alert(m.X); // undefined

I'd expect that _foo() would be called (and, if that ever happens, that the this variable in _foo() would be an instantiation of MyObject.

Does anyone know why this doesn't work, and of any alternative pattern for passing an object to an event handler?

Thank you for reading.

Brian

解决方案

As Kenny points out you're missing the new. You also need to make sure that this in _foo refers to the MyObject instance
One way to do it:-

function MyObject( input ) {
    var _this = this;
    input.change( function() {
       // explicitly set the `this` in _foo to `_this`
        _this._foo.call( _this );
    });
   this.X = undefined;
}

MyObject.prototype._foo = function( event ) {
   alert("This is called");
   // and 'this', being 'm', has X set to true
   this.X = true;
   // the textbox must be accessed by 'event.target' not 'this' if you need it
}

var test_input = jQuery("input#xyz"); // a random, existing input

var m = new MyObject(test_input); // attach handler (or try to)

test_input.change(); // trigger event

alert(m.X); // true

P.S You can't avoid using the new operator by leaving it out! :)

这篇关于jQuery / javascript事件 - 原型事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆