objectify

by ecropolis

HTML

<h2></h2>
<a>Go GREEN!</a>
<div></div>
<hr>
<ul id="log"></ul>

CSS

body { font-family: arial, sans-serif; }
div {  height: 20px; padding:15px 25px; width: 5px; background-color: #CCC; margin: 20px; border-radius: 6px; }
div.gogreen { background-color: #bada55; }
a { padding: 2px 4px; border: 2px solid #bada55; border-radius: 6px; }
a, div.gogreen { cursor: pointer; }
div span { font-size: .7em; }

JavaScript

myScope = {
    init: function() {
        console.log(this.doThings('sam').sayHelloTo('Warren G.'));
        console.log(this.doThings().s);
        $('h2').html( this.doThings('sam').sayHelloTo('warren') );
        this.bindInitialEvents();
    },
    bindInitialEvents: function(){
        $('a').on('click',function(e){ 
            myScope.domStuff(e).goGreen('div');  
        });
    },
    domStuff: function(event){            
        if(typeof event != 'undefined'){
            console.log(event);
            event.preventDefault();
        }
        this.goGreen = function(sel){
           console.log('go green');
           var $ele = $(sel);
           $ele.addClass('gogreen').html('<span>undo</span>')
               .on('click', myScope.domStuff().goBack);
            return false;
        }
        this.goBack = function(e){
           if(typeof e != 'undefined')
               console.log(e);
           console.log('NO Green');
           $ele = $('div');
           $ele.removeClass('gogreen').empty().unbind();
            return false;
        }
        return this;
    },
    doThings:function(a){
       var yourname = a;
       this.s = 'cool stuff';
       this.sayHelloTo = function(myname){
          return 'hello ' + (myname != undefined ? myname : yourname) + '!';
       }
       return this;
    }
};

myScope.init();

tests = function() {
    myScope.domStuff().goGreen('div');
    $log.prepend( '<li>test-> goGreen(): '+($('div').hasClass('gogreen') ? 'true':'false')+'</li>' );
    myScope.domStuff().goBack();
    $log.prepend( '<li>test-> goBack(): '+($('div').hasClass('gogreen') ? 'false':'true')+'</li>' );
    $log.prepend( '<li>test-> sayHelloTo(\'Warren\'): '+(myScope.doThings().sayHelloTo('Warren') == 'hello Warren!' ? 'true':'false')+'</li>' );
}
$log = $('#log');
tests();