Using Troop

Sample code for Troop. https://github.com/production-minds/troop

by Dan Stocker

HTML

<script src="https://dl.dropbox.com/u/9258903/JavaScript/dessert-0.3.2.js"></script>
<script src="https://dl.dropbox.com/u/9258903/JavaScript/troop-0.6.1.js"></script>

JavaScript

var 
    // base class by extending base in troop
    myBase = troop.Base.extend()
        // adding static constants
        .addConstants({
            rightAngle: 90
        })
        // adding methods    
        .addMethods({
            // constructor, mandatory for non-static classes
            init: function() {
                this.addPrivate({
                    _foo: "bar"
                });
            },
            foo: function() {
                $('body').append(this._foo + '<br />');
            }
        }),
    
    // child class by extending myBase
    myChild = myBase.extend()
        .addMethods({
            // init now accepts argument
            init: function(place) {
                // calling base class constructor
                myBase.init.call(this);
    
                // argument ends up as public property on instance
                this.addPublic({
                    hello: place
                });
            },
            greet: function () {
                $('body').append("hello " + this.hello);
            }
        });

// instantiating myBase
myBaseInstance = myBase.create();
myBaseInstance.foo(); // outputs "bar"

// instantiating myChild
// arguments passed to .create are forwarded to .init
myChildInstance = myChild.create("world");
myChildInstance.greet(); // outputs "hello world"

// logging to console (Chrome recommended)
console.log('myBase', myBase, 'myChild', myChild);
console.log('myBaseInstance', myBaseInstance, 'myChildInstance', myChildInstance);