对Function的几个有用的扩展(2)

来源:互联网 发布:妹子升级数据 编辑:程序博客网 时间:2024/05/21 22:46

2、bindBefore(bindAfter):将一个方法绑定到另一个方法上,使之在被绑定的方法之前(后)运行。

bindBefore(bindAfter)的最典型应用场景是:某一事件需要绑定若干个方法,且必须保证运行顺序,先执行方法A,再执行方法B。传统的addEventListener虽然能够将这些方法绑定到特定对象上,却不能保证执行顺序(关于事件函数的执行顺序,不同的浏览器有不同的规则)。我们可以将事件方法先bindBefore (bindAfter)之后,再addEventListener,可以解决这一问题。

使用方法: newFunction = functionA.bindBefore(functionB,caller,arg1,arg2,......);

例:

var functionA = function(){
          alert("run me next");
}

var functionB = function(){
        alert("run me first");
}

var but = document.getElementById("demoButton");

if(but.onclick)but.onclick = but.onclick.bindAfter(functionA.bindBefore(functionB));
else but.onclick = functionA.bindBefore(functionB);

绑定后的onclick执行顺序是:1、原有的onclick事件函数(如果有);2、functionB;3、functionA

需要说明的是,如果要“阻止”后续方法的执行,只要将本方法返回false即可。可以在bindBefore(bindAfter)时指定caller和参数(未指定时,caller为windows),在事件函数允许时,该函数的this将指向caller.

3、bindAsEventListener

本扩展需要解决的问题是:在多Frame的页面中,我们可能需要在FrameA中响应FrameB中的事件。并在FramA中对FrameB中的事件源进行某些处理和操作。

bindAsEventListener在事件发生时,抓取事件,即使它在其他Frame中。然后将event对象和发生事件的document对象传递给事件处理函数。

 例:

var eventFunc = function(evt,Document){
         
var target = new Event(evt).target;    // Event:jscriptFrame中定义的事件类,后述。
         target.doc = Document;
}


parent.Frame(
1).window.document.getElementById("demo").onclick = eventFunc.bindAsEventListener(window);

同样,bindAsEventListener也可以指定caller.未指定时为window.

4、join

本扩展将两个方法的返回值以某个固定的连接词以字符串的形式连接起来。

例:

var funcA = function(){
      
return "A"
}


var funcB = function(){
     
return "B";
}


var newfunc = funcA.join(funcB," join ");

newfunc()将返回 "a join b"。

可以在调用newfunc时指定funcA和funcB的caller,使方法中的this指向他们。

回头看看我们在Class基类中使用的这段代码:

  p.getClazz = c?function(){return def.getClassName + (this.classid?"(" + this.classid + ")":"");}.
                              join(s.getClazz,
" extend "):function(){return "unnamed Class extend " + s.getClazz()}

通过join完成了继承关系的描述。

原创粉丝点击