modelfactory
Data models with schema definition, and event propagation inspired by Mongoose & Backbone.js
Installation
Install with component:
$ component install pgherveou/modelfactory
Install with npm:
$ npm install modelfactory
Example
var modelfactory = regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; // create a User Model var User = modelfactory // define virtualsUserschema // define gettersUserschema; // define settersUserschema; // define static methodsUserschema; // define instance methodsUserschemamethod'greeting' {return 'hello ' + thisnamefull;}; // create an instancevar user = email: "john@gmail.com"name: first: 'john' last: 'mcenroe'trophies: name: 'Roland Garros' date: 'june-1984' name: 'Wimbledon' date: 'aug-1984'; // data are casted according to their typeuserage = "56"userage === 56 // trueuserdate = 'oct-2013'userdate instanceof Date // true // events are emitted on ppty changeuser;useremail = 'johny@gmail.com'user // or silent it // work for nested properties as welluser;user;usernamefirst = 'johny' // or embedded arraysusertrophies;usertrophies; // validation use schema rulesuseremail = "johnyatgmail.com";console; // KO
reuse mongoose schema definition
You can share your schema definition between node and the browser here is one way of doing it
/*! * user.shared.js */ module { var User = email: type: String lowercase: true match: emailRegex firstname: type: String min: 2 lastname: type: String min: 2 ; User; Usermethod'greating'; return User;};
/*! * user.server.js */ var mongoose = User = mongooseSchema; // create a uservar user = email: 'pg@jogabo.com' firstname: 'PG' lastname: 'Herveou'; // ... // play with useruserfullname; // => PG Herveouuser; // => no errsuser;
/*! * user.client.js */ var factory = User = factorySchema; // add some client specific methodsUserprototype { /* ... */ }; // create a uservar user = email: 'pg@jogabo.com' firstname: 'PG' lastname: 'Herveou'; // ... userfullname; // => PG Herveouuser; // => no errs // do something when firstname changeuser; // => trigger change:firstname eventuserfirstname = 'Pierre-Guillaume';user;
Reuse models & ref / populate
Usually you set your client model with populated objects coming from the server Here is an example of a Post model that reference a User model.
/*! * post.shared.js */ module { return date: type: Date required: true msg: type: String trim: true required: true ;};
/*! * post.server.js */ var mongoose = schema = mongooseSchema; schema
/*! * post.client.js */ var factory = User = schema; schema = factory; schema;moduleexports = schema;
API
coming soon..
supported browsers
should work on any browser supporting Object.defineProperty
Credits
License
MIT