Objects

To create an edb.Object constructor, simply extend from edb.Object.

var Person = edb.Object.extend({
	firstname: '',
	lastname: '',
	fullname: function() {
		return [this.firstname, this.lastname].join(' ');
	}
});

An instance of Person can now be created with a JSON argument.

var person = new Person({
	firstname: 'John',
	lastname: 'Johnson'
});
console.log(person.fullname()); // John Johnson

Typed properties

We can also declare typed properties. Typically like this:

var Person = edb.Object.extend({
	friend: Person
	// (firstname, lastname, fullname etc.)
});

This example will however not really work. That's because the Person constructor doesn't exist before it has been declared, but we can work around this by writing directly to the prototype.

var Person = edb.Object.extend(/* extensions */);
Person.prototype.friend = Person;

Two Person instances can now be created with a single argument.

var person = new Person({
	firstname: 'John',
	lastname: 'Johnson',
	friend: {
		firstname: 'Bob',
		lastname: 'Schmidt'
	}
});
console.log(person.fullname()); // John Johnson
console.log(person.friend.fullname()); // Bob Schmidt

The typed properties can also be an edb.Array. We haven't prepared such a constructor, but we can declare one anonymously.

var Person = edb.Object.extend({
	friends: edb.Array.extend({
		$of: Person
	});
});

We can now create as many Person instances as we like with a single JSON argument. Note that the value of friends must now be an array.

var person = new Person({
	firstname: 'John',
	lastname: 'Johnson',
	friends: [
		{ firstname: 'Bob', lastname: 'Schmidt' },
		{ firstname: 'Ole', lastname: 'Honnoré' },
		{ firstname: 'Jim', lastname: 'Nielsen' },
	]
});
console.log(person.friends[2].fullname()); // Jim Nielsen

Untyped properties

If no Types are a assigned to the properties, objects and arrays found in JSON will be newed up as either an edb.Object or an edb.Array. If you don't want this, you must declare them as simple objects/arrays.

var Person = edb.Object.extend({
	friend: Object,
	friends: Array
});

If you're not planning to observe these properties, and if they contain a lot of data, it's generally adviced to declare them as simple properties.

Anonymous Objects

As we have seen, Type subclasses can be create anonymously.

Person.prototype.friend = Person.extend({
	fullname: function() {
		return 'Friendly ' + this.super.fullname();
	}
});
var person = new Person({
	friend: {
		firstname: 'Bob',
		lastname: 'Schmidt',
	}
})
console.log(person.friend.fullname()); // Friendly Bob Schmidt