model.js

I’m working on a quick alternative to heavy frameworks like ExtJS and Backbone called model.js, it’s more or less just a simple library/script at the moment. It allows you to pass in JSON objects to create classes in which all class objects begin with a nice event model. It’s design to be tiny and relatively simple.

UPDATE: model.js now has a home -> modeljs.org

GitHub: model.js

Here’s a quick example:

// Start by using the createClass() method of model.js to create our class
var TestClass = model.createClass({
	construct: function(props) {
		this.apply({
			defaultProp: 'hello world!'
		}, props || {});
 
		console.log('Constructed!');
	},
	myMethod: function() {
		console.log(this.defaultProp);
	}
});
 
// Next we create a class object from our class we created with model.js
var testObject = new TestClass();
/*
Output:
Constructed!
*/
 
testObject.myMethod();
/*
Output:
hello world!
*/
 
var ExtendedClass = TextClass.extend({
	construct: function(props) {
		// Run superclass constructor.  (Run the original constructor we are overriding)
		this.superclass.construct.apply(this, arguments);
	},
	myMethod: function(){
		console.log('Overridden!');
	}
});
 
var testObject2 = new ExtendedClass();
/*
Output:
Constructed!
*/
 
testObject2.myMethod();
/*
Output:
Overridden!
*/
 
console.log(textObject2.defaultProp);
/*
Output:
hello world!
*/
 
// Now a briefing of event listeners!
 
testObject.on('myEvent', function(arg){
	console.log('myEvent Fired!');
	console.log('arg: ' + arg);
});
 
testObject.fire('myEvent', 'haha!');
/*
Output:
myEvent Fired!
arg: haha!
*/

You can also call onSingle(), which is exactly the same as on() except it will detach the event listener when the event is fired. Both on() and onSingle() return an event event object, which can be passed as an argument to un() to detach the event.

Example:

var listener = testObject.on('myEvent', function(){});
testObject.un(listener);

Thank you for checking out model.js, I will be adding more functionality and proper documentation in the near future!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">