0

I am trying to create a JS framework.

Here is my JS code:

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

Here I am calling this Framework

    <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>

OUTPUT

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

The problem is btn1 click event is not working but btn2 click is working. Can somone suggest some solution or some better way to make a JS frame work?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Manish Kumar
  • 10,214
  • 25
  • 77
  • 147

1 Answers1

0

The problem is btn1 click event is not working

Well, you were not attaching a listener to it. You did pass a function to the controller method which could have done this, but it was never called.

controller: function(pl) {
    if (typeof pl.events === 'function') {
        console.log('event is function'); // but do nothing?
        // add this:
        pl.events();
    }
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • one more thing why **window id == test** and **id == test** both are executing inside constructer while i am using **$('test')** only once – Manish Kumar Sep 18 '13 at 15:48
  • If you call it without `new`, ie. `$('test')`, then that "window id == test" branch will execute and call `new $('test')`… Btw, you better should use `if (!(this instanceof $)) return new $(id);`. – Bergi Sep 18 '13 at 16:09
  • Maybe have a look at [this question](http://stackoverflow.com/a/18877343/1048572)… – Bergi Sep 18 '13 at 16:48
  • but why **console.log('window id == '+id);** and **console.log('id == '+id);** both are executing when i use **$('test')**. I think only one should be executed because its ** return new $(id);** a returning statement so it should not go to next line – Manish Kumar Sep 19 '13 at 05:03