Skip to content

Repository files navigation

Caplet.js

Caplet is a tiny (11kb) modeling library.

Build StatusCoverage StatusDependency StatusGitter

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)).

Why?

  • 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.

Installation

npm install caplet

Examples

Extensions

Basic Example

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);

API

Model Caplet.createModelClass(properties)

creates a new model class

  • properties - prototype properties to set on the new class
    • mixins - array of mixins to add - adds to the prototype of class

Model()

creates a new model

varmodel=newModel();// this is validvarmodel=Model();// you can also omit the "new" keyword

Model.initialize()

called when the model is instantiated

varModel=Caplet.createModelClass({initialize: function(){// initialize stuff here}});Model();// initialize() called

Model.fromData(data)

called when the data property is set. This method deserializes data and sets the returned object as properties on the model.

Note that uid should 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 prop

Model.toData()

Serializes 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};}});

Model.onDataChange(newData, oldData)

called when the data property changes

Model.toJSON()

calls toData()

Model.get(property)

returns a property

Model.set(property, value)

sets a property value

Model.data

unserialized data on the model

Model.setProperties(properties)

sets multiple property values

disposable Model.watch(listener)

watches the model for any changes

varm=newCaplet.Model({name: "Oprah"});m.watch(function(){console.log("changed!");});m.set("name","Ryan");// triggers watcher

Model.dispose()

disposes the model - also removes it from a collection if it is in one

Collection Caplet.createCollectionClass(properties)

creates a new collection class

  • properties - prototype properties to set on the new class
    • mixins - array of mixins to add - adds to the prototype of class

Collection()

creates a new collection

varcollection=newCollection();varcollection=Collection();

Collection.initialize()

called when the collection is created

Collection.fromData(data)

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))};}});

Collection.onDataChange(newData, oldData)

called when the data property changes

Collection.modelClass

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]

Collection.source

the source of the collection

Collection.onChange()

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);// true

Collection.at(index)

returns a model at the given index

Collection.filter(fn)

filters the collection

Collection.push(model)

pushes a model onto the collection

Collection.unshift(model)

unshifts a mdoel

Collection.splice(index, numToRemove[, ...replace])

Removes / replaces items in the collection

Collection.map(fn)

maps & returns values

Collection.source

source of the collection (array of models)

Collection.data

raw unserialized data

Helpers

Caplet.setVirtuals(target, virtuals)

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 property

Caplet.watchProperty(target, property, listener)

watches a property on the model or collection

Caplet.load(target, load, onLoad)

varPerson=Caplet.createModelClass({load: function(onLoad){Caplet.load(this,function(onLoad){$.get("/people/"+this.uid,onLoad);},onLoad);}})

Caplet.watchModelsMixin

React mixin which automatically watches properties on a component & triggers a re-render if anything changes

About

Universal models library

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages