2012. december 10., hétfő

Protain - defining node-classes

So, we have arrived to the subject in which Protain tries to bring something different. Node-based class behaviour.
Sounds so advanced that I threw my brain, went after it and threw it again... =)

Let's quickly create 2 nodes in a namespace, mine will be same as in the previous tutorials - I won't comments in these now:
protain
    .node(this, 'name', {
        getName: function () {
            return this.name;
        },
        setName: function (name) {
            this.name = name;
            return this;
        }
    })
    .node(this, 'guid', function () {
        var id = 0;
    
        return {
            generateId : function () {
                this.ID = id++;
                return this;
            }
        }
    }());
First thing you want to keep in mind is that classes are able to inherit from nodes only in the same namespace!

Then when you create a class, you just "list" the nodes you want to use for that class. Also, you still have the .define or .init methods available for custom class property definitions:
/**
 * defining a "node class"
 */
protain
    .class(this, 'MyFirstNodedClass', 'guid', 'name')
    /**
     * defines a property on the class
     */
    .define({
        CLASS_NAME: 'MyFirstNodedClass'
    })
    /**
     * @constructor
     */
    .init(function (instance, name) {
        /**
         * setting some instance properties
         */
        instance
            .generateId()
            .setName(name + ' ' + (instance.ID + 1));
    });
This was very hard, right? =) Now, let's see it in action by generating 10 instances in a loop and logging it out to the console:
/**
 * instantiating 10 instances and logging them out
 */
for (var i = 0; i < 10; i++) {
    console.log(
        /**
         * logging a new instance
         */
        protain
            .class(this, 'MyFirstNodedClass')
            .create('Some random name')
    );
}
Node-based class behaviour (I'm still wet...) is quiet simple I guess... =) You are also able to extend classes from each other but that belongs to another article...

Find Protain on GitHub: https://github.com/benqus/protain

Nincsenek megjegyzések:

Megjegyzés küldése