Service Encapsulation
jquery.model.encapsulateModels encapsulate your application's raw data. This promotes reuse and provide a standard interface for widgets to talk to services.
Models encapsulate your application's raw data. This promotes reuse and provide a standard interface for widgets to talk to services.
The majority of the time, the raw data comes from services your server provides. For example, if you make a request to:
The server might return something like:
In most jQuery code, you'll see something like the following to retrieve contacts data:
Instead, model encapsulates (wraps) this request so you call it like:
And instead of raw data, findAll returns contact instances that let you do things like:
Encapsulation Demo
The Grid demo shows using two different models with the same widget.
How to Encapsulate
Think of models as a contract for creating, reading, updating, and deleting data.
By filling out a model, you can pass that model to a widget and the widget will use the model as a proxy for your data.
The following chart shows the methods most models provide:
By filling out these methods, you get the benefits of encapsulation, AND all the other magic Model provides.
There are two ways to fill out these methods:
Using Templated Service URLS
If your server is REST-ish, you can simply provide urls to your services.
The following shows filling out a Task model's urls. For each method it shows calling the function, how the service request is made, and what the server's response should look like:
You can change the HTTP request type by putting a GET, POST, DELETE, PUT like:
Note: Even if your server doesn't respond with service data in the same way, it's likely that $.Model will be able to figure it out. If not, you can probably overwrite [jQuery.Model.static.models models] or [jQuery.Model.static.model model]. If that doesn't work, you can always implement it yourself.
Implement Service Methods
If providing a url doesn't work for you, you might need to fill out the service method yourself. Before doing this, it's good to have an understanding of jQuery's Ajax converters and deferreds.
Lets see how we might fill out the
Contact.findAll
function to work with JSONP:If we wanted to make a list of contacts, we could do it like: