繁体   English   中英

JavaScript事件库“ unidentified”

[英]Javascript event library 'unidentified'

我一直在研究事件处理的JavaScript库。 这是一些代码:

01| (function(){
02|     var int,
03|         Jist = function(s){
04|             return new Jist.fn.init(s);
05|         };
06|     Jist.fn = Jist.prototype ={
07|         init : function(s){
08|             if(!s){
09|                 return this;
10|             }
11|             else{
12|                 this.length = 1;
13|                 if (typeof s === "object"){
14|                     this[0] = s;
15|                 }
16|                 else if(typeof s === "string"){
17|                     var obj;
18|                     obj = document.querySelectorAll(s);
19|                     this[0] = obj;
20|                     this.elem = this[0];
21|                 }
22|                 return this;
23|             }
24|         },
25|     };
26|     Jist.fx ={
27|         event : function(event,callback,state){
28|             var dummy = (state) ? false : state; 
29|             for(var i=0; i<this.elem.length; i++) {
30|                 this.elem[i].addEventListener(event,callback,dummy);
31|             }
32|             return this;
33|             },
34|     }
35|     Jist.fn.init.prototype = Jist.fn;
36|     Jist.fn.init.prototype = {
37|         print : function(txt){
38|             for(var i=0; i<this.elem.length; i++) {
39|                 this.elem[i].innerHTML = txt;
40|             }
41|             return this;
42|         },
43|         click : function(callback){
44|             Jist.fx.event("click",callback);
45|             return this;
46|         },
47|     };
48|     window.Jist = window._ = Jist;
49| })();

然后在我的网页上,我必须对其进行测试:

01| <div id="enter">Begin!</div>
02| <script>
03|    _("#enter").click(function(){
04|       _("#enter").print("It worked!");
05|    })
06| </script>

似乎应该可以,但是我收到一条错误消息: 'undefined' is not an object (evaluating this.elem.length)[line 29 in the library]

有谁知道我该如何解决?

非常感谢您的帮助。

谢谢。

当您调用Jist.fx.event("click",callback); 它开始执行的event方法this将是Jist.fx ,它有没有属性命名elemevent方法试图当它引用使用this.elem.length 这会导致您看到错误。

this.elem不在函数范围内,因此返回未定义的错误,因此this.elem.length使用jist.elem.lengh代替jist.elem.lengh并检查

问题是,在event方法this并不是指你想要的对象集,则可以使用一个固定Function.call()

您需要更改对事件注册方法的调用,例如

Jist.fx.event.call(this, "click", callback);

另外,您还需要确保在将dom加载到目标元素后调用事件注册代码

演示: 小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM