JavaScript:简单框架无法正常工作

JavaScript:简单框架无法正常工作,javascript,prototype,javascript-framework,Javascript,Prototype,Javascript Framework,我正在尝试创建一个JS框架 这是我的JS代码: function $(id) { var info={ version:1.0 } if(id) { if(window === this) { console.log('window id == '+id); return new $(id); } console.log('id == '+id); this.e = document.getEl

我正在尝试创建一个JS框架

这是我的JS代码:

function $(id)
{
  var info={
     version:1.0
  }

  if(id)
  {
    if(window === this)
    {
        console.log('window id == '+id);
        return new $(id);
    }

    console.log('id == '+id);
    this.e = document.getElementById(id);
    return this;
  }
  else{
         return info;
   }
}



$.prototype={
    controller:function(pl)
    {
       if(typeof pl.events === 'function')
       {
        console.log('event is function');
       }
    },
    click:function(callback)
    {       
        this.e.addEventListener('click', callback, false);
        return this;
    }   
};
这里我称之为这个框架

    <div id='test'>
        <div id='btn1'>Button1</div>    
    </div>
    <div id='btn2'>Button2</div>


    <script>            
        $('test').controller({
            events:function()
            {
                $('btn1').click(function(){
                    alert('btn1 clicked');
                }); 
            }
        }); 

        $('btn2').click(function(){
            alert('btn2 clicked');
        });             

    </script>
问题是,btn1单击事件不起作用,但btn2单击起作用。有人能提出一些解决方案或更好的方法来实现JS框架吗

问题是btn1单击事件不起作用

嗯,你没有给它附加一个侦听器。您确实向
控制器
方法传递了一个函数,该方法本可以执行此操作,但它从未被调用

controller: function(pl) {
    if (typeof pl.events === 'function') {
        console.log('event is function'); // but do nothing?
        // add this:
        pl.events();
    }
}

这与它没有任何关系,不是吗?它的原生js原型不是你所说的。还有一件事,为什么当我使用$('test')时,window id==test和id==test都在构造函数中执行,只有当你调用它时没有
new
,即
$('test')
,那么“window id==test”分支将执行并调用
new$('test')
…顺便说一句,如果(!(this instanceof$)返回新$(id),最好使用
。也许可以看看…但是为什么控制台.log('window id=='+id);和console.log('id='+id);当我使用$('test')时,两者都在执行。我认为应该只执行一个,因为它**返回新的$(id);**返回语句,因此不应转到下一行
controller: function(pl) {
    if (typeof pl.events === 'function') {
        console.log('event is function'); // but do nothing?
        // add this:
        pl.events();
    }
}