【问题标题】:JavaScript: simple framework is not working properlyJavaScript:简单的框架无法正常工作
【发布时间】:2013-09-23 07:05:46
【问题描述】:

我正在尝试创建一个 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>

输出

window id == test
id == test
event is function
window id == btn2
id == btn2

问题是btn1点击事件不起作用,但btn2点击起作用。有人可以提出一些解决方案或更好的方法来使 JS 框架工作吗?

【问题讨论】:

  • 这和prototype.js没有任何关系吧?
  • 它的原生 js protoype 不是你说的

标签: javascript prototype javascript-framework


【解决方案1】:

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

嗯,你没有给它附加一个监听器。您确实将一个函数传递给了可以执行此操作的 controller 方法,但它从未被调用过。

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

【讨论】:

  • 还有一件事为什么 window id == testid == test 在我使用 $( 'test') 只有一次
  • 如果你在没有new的情况下调用它,即。 $('test'),然后那个“window id == test”分支将执行并调用new $('test')...顺便说一句,你最好使用if (!(this instanceof $)) return new $(id);
  • 也许看看this question...
  • 但是为什么 console.log('window id == '+id);console.log('id == '+id); b> 当我使用 $('test') 时,两者都在执行。我认为应该只执行一个,因为它 ** return new $(id);** 一个返回语句,所以它不应该转到下一行
猜你喜欢
  • 2011-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-11
  • 1970-01-01
相关资源
最近更新 更多