Caplet is a tiny (11kb) modeling library.
Caplet is the M in "MVC". It works independently from any other library, and can easily be used with your existing framework/view layer such as AngularJS, ReactJS, RactiveJS, or PaperclipJS (shameless plug).
Caplet doesn't make any assumptions about your code. It just gives organization to your model relationships in a sane way. It also gives you a relatively higher level of encapsulation for your data, while also encouraging you, but not forcefuly, to follow design patterns that scale quite well.
Caplet has been an evolution of many libraries in the past, which have been used in a few pretty large applications (30k-ish loc). The first version came about sometime around 2013 as mojo-models, and has since been further generalized for all intensive purposes.
The newer, hip version of Caplet has been designed for React, and pairs wells with the Hierarchial nature of React-based applications.
Caplet can be a great companion to Flux. It also serves as a Flux alternative if you enjoy the good 'ol (and well proven when done right) MVC approach (Caplet (M) + React (VC)).
- Scales. Concepts have been used in various apps consisting of ~30k LOC.
- Simple. You just have models & collections. Nothing else to learn.
- Familiar. Caplet isn't too inventive. If you're familiar with Symfony, Mongoose, or Ember, then Caplet shouldn't be tough to learn.
- Obvious. It's easier to reconcile how your application should be structured if the only thing you have to deal with are
models&collections. - Encapsulated. Caplet was design to encourage you to focus how your models & collections relate to one other versus how they relate to other parts of your application - this includes views, and even the API. This allows you to:
- Re-use your models for other applications - web/desktop/server-side.
- Maintain your model structure even if the API changes.
- Write your front-end in parallel with your API.
- Lightweight. Caplet is small (11 KB minified).
- Testable. Run 'em in the browser, in node, wherever you want.
npm install caplet
- meshlet - mesh + caplet mixin
- mesh - streamable data store library
- socket.io - realtime data
- http - HTTP (API) adapter
- local storage local storage db
- loki - loki in-memory db
varCaplet=require("caplet");varReact=require("react");/** */varTodoModel=Caplet.createModelClass({});/** */varTodoCollection=Caplet.createCollectionClass({modelClass: TodoModel,create: function(properties){vartodo=this.createModel(properties);this.push(todo);returntodo;}});/** */varTodoComponent=React.createClass({mixins: [Caplet.watchModelsMixin],render: function(){return<li><ahref="#"onClick={this.props.todo.dispose.bind(this.props.todo)}>x</a>{this.props.todo.text}</li>}});/** */varTodosComponent=React.createClass({mixins: [Caplet.watchModelsMixin],handleKeyDown: function(event){if(event.keyCode!==13)return;this.props.todos.create({text: this.refs.todoText.getDOMNode().value});},render: function(){return<div><inputtype="text"ref="todoText"onKeyDown={this.handleKeyDown}/><ul>{this.props.todos.map(function(todo){return<TodoComponenttodo={todo}/>;})}</ul></div>}});/** */React.render(<TodosComponenttodos={TodoCollection({data: [{text: "drive car"},{text: "wash car"}]})}/>,document.body);creates a new model class
properties- prototype properties to set on the new classmixins- array of mixins to add - adds to the prototype of class
creates a new model
varmodel=newModel();// this is validvarmodel=Model();// you can also omit the "new" keywordcalled when the model is instantiated
varModel=Caplet.createModelClass({initialize: function(){// initialize stuff here}});Model();// initialize() calledcalled when the data property is set. This method deserializes data and sets the returned object as properties on the model.
Note that
uidshould be set for an existing model
varAddress=Caplet.createModelClass({// impl here});varPerson=Caplet.createModelClass({fromData: function(data){return{uid : data._id,firstName : data.firstName,lastName : data.lastName,address : Address({data: data.address})};}});varperson=Person({data: {_id : "dbId",firstName : "Jeff",lastName : "Gordon",address : {city : "San Francisco",state : "CA",zip : 94114}}});console.log(person.firstName);// Jeffconsole.log(person.lastName);// Gordonconsole.log(person.address);// [object Address]console.log(person.data);// data propSerializes the model back into data.
varPerson=Caplet.createModelClass({toData: function(data){return{_id : this.uid,firstName : this.firstName,lastName : this.lastName,address : this.address ? this.address.toData() : void0};}});called when the data property changes
calls toData()
returns a property
sets a property value
unserialized data on the model
sets multiple property values
watches the model for any changes
varm=newCaplet.Model({name: "Oprah"});m.watch(function(){console.log("changed!");});m.set("name","Ryan");// triggers watcherdisposes the model - also removes it from a collection if it is in one
creates a new collection class
properties- prototype properties to set on the new classmixins- array of mixins to add - adds to the prototype of class
creates a new collection
varcollection=newCollection();varcollection=Collection();called when the collection is created
deserializes properties on the collection. This is already set, but you can easily override it.
varPeople=Caplet.createCollectionClass({fromData: function(data){return{anotherProp: "blah",source: data.source.map(function(data){returnthis.createModel({data: data});}.bind(this))};}});called when the data property changes
The model class to instantiate for each data item
varPerson=Caplet.createModelClass();varPeople=Caplet.createCollectionClass({modelClass: Person});varpeople=People({data: [{name: "Ben"},{name: "Carmen"}]});console.log(people.at(0));// [object Person]the source of the collection
override this if you want to listen for any changes on the collection
varTodo=Caplet.createModelClass({toggleComplete: function(){this.set("complete",!this.complete);}});varTodos=Caplet.createCollectionClass({modelClass: Todo,getInitialProperties: function(){return{allComplete: this._isAllComplete();}},onChange: function(){this.setProperties(this.getInitialProperties());},_isAllComplete: function(){for(vari=this.length;i--;)if(!this.at(i).complete)returnfalse;returntrue;}});vartodos=Todos({data: [{text: "wash car"},{text: "buy groceries","complete": true}]});console.log(todos.allComplete);// falsetodos.at(0).set("complete",true);console.log(todos.allComplete);// truereturns a model at the given index
filters the collection
pushes a model onto the collection
unshifts a mdoel
Removes / replaces items in the collection
maps & returns values
source of the collection (array of models)
raw unserialized data
Sets virtual properties which get called on demand
varPeople=Caplet.createCollectionClass({load: function(){Caplet.load(this,function(next){$.get(this.person ? "/people/"+this.person.uid+"/friends" : "/people",next);})}});varPerson=Caplet.createModelClass({initialize: function(){Caplet.setVirtuals(this,{friends: function(onLoad){People({person: this}).load(onLoad);}})}});varperson=Person({uid: "personId"});person.watch(function(){console.log(person.get("people"));// should be defined});person.get("people");// trigger virtual propertywatches a property on the model or collection
varPerson=Caplet.createModelClass({load: function(onLoad){Caplet.load(this,function(onLoad){$.get("/people/"+this.uid,onLoad);},onLoad);}})React mixin which automatically watches properties on a component & triggers a re-render if anything changes