30-讨论
9.7.3 讨论
1.节点到哪里去了
你迟早都会提这个问题。前面已经提到过,当向 bind() 传递一个作用域对象时,事件处理程序的 this 将被覆盖。这意味着无法像往常那样读取该节点……但是这个节点并没有丢失。
当向 bind() 方法传递一个作用域对象时,事件将向作用域对象提交事件处理程序的 this 。仍然可以使用 event.currentTarget 属性确定提交给事件的元素,该属性包含对该DOM元素的引用。
这通常没有必要,因为使用 this 更简短,但是在这类情况下,这是唯一的出路。
2.示例
我将创建一个小的示例,说明使用作用域参数的方法,并说明它适用的场合。
对象 。例如,需要两个对象,每个对象都有一个将要作为事件处理程序绑定的方法:
这些对象如下:
function Person(name){
this.name = name;
this.married = false;
}
jQuery.extend( Person.prototype, {
whatIsYourName: function(){
alert(this.name);
},
updateMarriedState: function(e){
var checkbox = e.currentTarget;
this.married = checkbox.checked;
}
});
var peter = new Person('Peter');
var susan = new Person('Susan');
绑定方法 。假定有某种表单,表单上有两个复选框( #c1 和 #c2 )。每个复选框操纵上述对象之一的 married 状态。
jQuery('#c1').bind('change', peter.updateMarriedState, peter);
jQuery('#c2').bind('change', susan.updateMarriedState, susan);
由于有作用域属性,因此不需要为每次绑定创建新的函数;可以使用对象方法来代替。
这些方法甚至不需要从一开始就附加到对象中。可以这样做:
function updatePersonMarriedState(e){
var checkbox = e.currentTarget;
this.married = checkbox.checked;
}
jQuery('#c1').bind('change', updatePersonMarriedState, peter);
jQuery('#c2').bind('change', updatePersonMarriedState, susan);
正如你所看到的,你实际上并不一定要将这些函数放入对象原型中,保持它们的独立也有实际意义。为什么属于 Person 的一个方法应该知道复选框和节点的情况?将具体的DOM操纵与数据分离可能更好。
在某些情况下,对象方法完全不必了解节点或者事件对象。在这种情况下,可以直接绑定一个方法,完全不必将DOM与数据混在一起。
如果有两个按钮( #b1 和 #b2 ),单击它们时应该显示一个人的姓名,这可以简单地实现:
jQuery('#b1').bind('click', peter.whatIsYourName, peter);
jQuery('#b2').bind('click', susan.whatIsYourName, susan);
值得一提的是,这两个方法实际上相同:
peter.whatIsYourName == susan.whatIsYourName; // true
该函数只创建一次,并保存到 Person.protype 中。
[1] http://en.wikipedia.org/wiki/Encapsulation_(computer_science)。
[2] http://plugins.jquery.com/project/mousewheel。
[3] http://plugins.jquery.com/project/drag,http://plugins.jquery.com/project/drop。
[4] http://flesler.blogspot.com/2008/02/jqueryserialscroll.html。
[5] http://en.wikipedia.org/wiki/Closure_(computer_science)。
[6] http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-eventgroupings-mutationevents。
[7] http://en.wikipedia.org/wiki/Aspect_oriented_programming。