Javascript事件库'unidentified' [英] Javascript event library 'unidentified'

查看:107
本文介绍了Javascript事件库'unidentified'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究用于事件处理的JavaScript库。以下是一些代码:

I have been working on a javascript library for event handling. Here is some of the code:

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| })();

然后在我的网页上,我需要测试它:

And then On my webpage, here is what I have to test it out:

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

看起来这应该可行,但我收到的错误是:'undefined'不是对象(评估this.elem.length)[库中的第29行]

It seems like this should work, but instead I get an error that reads: 'undefined' is not an object (evaluating this.elem.length)[line 29 in the library]

有谁知道我是怎么做的可以解决这个问题吗?

Does anyone know how I can fix this?

非常感谢帮助。

谢谢。

推荐答案

问题出在事件方法这个不引用您想要的对象集,您可以使用 Function.call()

The problem is in the event method this does not refer to the object set you want, you can fix it using a Function.call()

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

You need to change the call to event registration method like

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

此外,您需要确保在dom加载目标后调用事件注册码元素

Also you need to make sure that the event registration code is called after the dom is loaded with the target element

演示:小提琴

这篇关于Javascript事件库'unidentified'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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