$.Model is the application data layer. It provides an easy way to connect to the services that provide RESTful APIs, listen to data changes, and bind HTML elements to models, deferrers, and validations.
$.Model is very handy; we don't need to manually write XHR calls using jQuery's Ajax method for instance. We can map our backend API using $.Model and then use its methods to pull/push data to the server.
We can organize $.Models with a list using $.Model.List
, which is similar to Backbone.js's collections (http://backbonejs.org/#Collection).
Let's write some code in the file jquerymx_playground_1.js
:
steal( 'jquery/model', 'jquery/dom/fixture', function ($) { $.Model('AccountModel', { findAll: 'GET /accounts', findOne: 'GET /accounts/{id}', create: 'POST /accounts', update: 'PUT /accounts/{id}', destroy: 'DELETE /accounts/{id}' }, { } ); // Fixtures (function () { var accounts = [ { id: 1, type: 'USD' }, { id: 2, type: 'EUR' } ]; // findAll $.fixture('GET /accounts', function () { return [accounts]; }); // findOne $.fixture('GET /accounts/{id}', function () { return accounts; }); // create $.fixture('POST /accounts', function () { return {}; }); // update $.fixture('PUT /accounts/{id}', function (id, acc) { return acc; }); // destroy $.fixture('DELETE /accounts/{id}', function () { return {}; }); }()); AccountModel.findAll({}, function (accounts) { $.each(accounts, function (i, acc) { $('<p>').model(acc).text(acc.type).appendTo('body'), }); }); AccountModel.bind('updated', function (e, acc) { acc.elements($('body')).remove(); }); AccountModel.bind('created', function (e, acc) { console.log('AccountModel.bind: event: ', e,'Account: ', acc); }); } );
Lets break down this code and see what happened here:
$.Model
is responsible for mapping API to our model.$.fixtures
are responsible for imitating server responses. Fixtures are very helpful when we need to start development without the web server API being ready or available.bind
method in the model
class is responsible for binding model methods update
and create
. We can try using them to see how they work from the web browser console by executing these methods on the instance of AccountModel
.18.227.79.241