Dependencies:
- jQuery (1.4.x)
- Underscore (for now)
The first thing to do is to create a model class using the factory 'Model()':
var Post = Model('post')
This allows you to create instances of 'post' models, and also contains an internal collection of all 'posts' which can be used for querying.
The next thing you need to do is create and manipulate instances of your new JS model. These actions should be fairly familiar to people who have used ActiveRecord.
var post = new Post({foo: 'bar'})
post.update({foo: 'bar' })
post.destroy()
Attributes are read with the attr method, which works in a similar way to JQuery on the DOM:
post.attr('foo'); // getter
post.attr('foo', 'bar'); // setter
The id of an object is set after persistence, and is accessible via the id() method.
Instances need to be fed back into the model's collection, so that the results are available to "finders". The 2 main methods which handle this are:
- Post.add(post)
- Post.remove(post.id())
These are called automatically after successful persistence, but can also be called manually.
Since state is held in the browser, objects need to be queried from our collection in order to be manipulated and used in the UI. This is where js-model is different to several other solutions. It is not a REST-based proxy for the objects on your server, and doesn't rely on constant HTTP requests to gather information. Instead it look up objects in its own cache.
Different finders are available
Post.all()
and
Post.find(id)
These are useful for iterating over the collection and finding specific objects, respectively. It is also possible to add custom finders to the collection's prototype (see below).
js-model allows you to listen to the lifecycle of objects, based on the events they trigger at different points.
It is possible to bind to an event occurring when adding an object to a collection. Eg:
Post.bind("add", function(new_object) {
add_object_into_ui(new_object)
})
and
Post.bind("remove", function(removed_object) {
remove_object_from_ui(removed_object)
})
Parts of your application can be bound to changes which happen to a specific instance:
my_object.bind('update', function(){ my_ui_elem.text(my_object.attr('name')) })
Including when the instance is destroyed:
my_object.bind('remove', function(){ my_ui_elem.remove() })
State can be persisted in a number of ways, including local storage. However, one of the most common uses is via REST to the originating server. js-model comes bundled with an optional REST persistence adaptor.
Setting up persistence for a given model is handled when the class is created:
var Post = Model('post', {
persistence: Model.RestPersistence("/posts")
}
Calling save or destroy on an object now fires a corresponding REST Request:
var post = new Post({foo: 'bar'})
post.save() // POST /posts
post.attr("foo", "baz").save() // PUT /posts/1
post.destroy() // DELETE /posts/1
A custom callback can be fed into the save method to execute on success or failure:
post.save(function(success) {
if (success) {
alert('yey')
} else {
alert('boo')
}
})
The default triggered events (mentioned earlier) are generally only called once persistence is successful.
You can also include named parameters in the URL that will pick up the corresponding values from the model instance:
var Post = Model("post", {
persistence: Model.RestPersistence("/categories/:category_id/posts")
}
var post = new Post({ title: "Foo", category_id: 2 })
// POST request made to /categories/2/posts
post.save()
It is possible to have local validations to avoid hitting your server unnecessarily.
To add your own validations you should define a custom validate
method that adds error messages to the errors
object. valid()
is called on save and checks that errors
is empty.
var Post = Model('post', {}, {
validate: function() {
if (this.attr("title") != "Bar") {
this.errors.add("title", "should be Bar")
}
}
})
var post = new Post()
post.attr("title", "Foo")
post.valid() // => false
post.errors.size() // => 1
post.errors.on("title") // => ["should be Bar"]
post.errors.all() // => { title: ["should be Bar"] }
post.attr("title", "Bar")
post.valid() // => true
post.errors.size() // => 0
post.errors.on("title") // => []
post.errors.all() // => {}
Since models are objects, there can be a need to give them custom public methods. There are two parts to a model which can be extended, and these are akin to instance and class methods on an ORM such as ActiveRecord.
These are defined by passing an object as the second argument when defining a model:
var Post = Model("post", {
find_by_foo: function(foo) {
return this.detect(function() {
return this.attr("foo") == foo;
});
}
}
Post.find_by_foo("bar")
Instance methods are the third argument when defining a model and are often used to link objects together in a way which mimics the relationships the data might have in the remote database ('has many' etc). However, they can be pretty much anything. These are defined on the model at class creation time, they are added to the model's prototype
overwriting the defaults if necessary.
var Post = Model("post", {}, {
foo: function() {
...
}
})
Post.find(3).foo()
You might also want to have custom events on objects, which are also possible:
post.trigger('turn_blue')
Which could be linked up to a UI element.