Original article: http://javascriptmvc.com/docs.html#&who=jQuery.Model
Liu guixue, liuguixue@gmail.com)
A model is a data layer used to encapsulate an application. For large applications, models are very important:
- Encapsulate the service, so that the control layer and view do not need to care about where the data comes from;
- Auxiliary functions are provided to simplify the operations and abstraction of original business data.
There are two implementation methods:
- Obtain data from service requests or interactions;
- Convert or encapsulate original business data into more useful forms;
Basic usage
The jquery. Model class provides a basic framework for organizing the data layer of your applications. First, let's look at an Ajax operation without considering the model. If we have an application, the requirements are as follows:
- Retrieves the task list;
- Displays the remaining days of each task;
- When the user clicks, the mark is complete.
Let's take a look at how the model is implemented:
$. Controller. extend ("MyApp. controllers. tasks ", {ondocument: true}, {// when the page load is complete, obtain all the tasks ready: function () {$. get ('/tasks. json', this. callback ('gottask'), 'json')},/* assume that JSON is an array, for example, * [{name: "trash", due_date: 1247111409283},...] */gottasks: function (JSON) {for (VAR I = 0; I <JSON. length; I ++) {var taskjson = JSON [I]; // calculate the remaining time var remainintime = new date ()-New Date (taskjson. due_date); // append to HTML $ ("# tasks "). append ("<Div class = 'task' taskid = '" + taskjson. ID + "'>" + "<label>" + taskjson. name + "</label>" + "due date =" + remainintime + "</div>") }}, // click it to mark completion. // when the task is completed, get ID, post a request, delete ". task click ": function (EL) {$. post ('/tasks/' + el. ATTR ('data-taskid') + '. JSON ', {complete: true}, function () {el. remove ();})}})
The code looks fine at this time, but if:
- Business changes?
- Is the remaining time calculated for other parts of the application?
- Do other tasks need to be obtained?
- Is the same task displayed in different places on the page?
The solution requires a powerful model layer. Before learning to write a model, let's see how the control layer of a beautiful model is implemented:
$.Controller.extend("MyApp.Controllers.Tasks",{onDocument: true},{ load: function() { Task.findAll({},this.callback('list')) }, list: function( tasks ) { $("#tasks").html(this.view(tasks)) }, ".task click" : function( el ) { el.model().update({complete: true},function(){ el.remove(); }); }})
The contents of the views/tasks/list. ejs file are as follows:
<% for(var i =0; i < tasks.length; i++){ %><div <%= tasks[i] %>> <label><%= tasks[i].name %></label> <%= tasks[i].timeRemaining() %></div><% } %>
Is this much better! Of course, these improvements are because we use views and make our controllers fully readable. Let's take a look at the model:
$.Model.extend("Task",{ findAll: "/tasks.json", update: "/tasks/{id}.json"},{ timeRemaining: function() { return new Date() - new Date(this.due_date) }})
This is better, because you can implement the Ajax function separately and encapsulate the data when the returned result is returned. Let's
Let's talk about each bold entry in the Controller and view.
Task. findall
The findall function of the task requests data from "/tasks. JSON". When the data is returned, the "wrapmany" function is executed before being passed to the callback function after success.
If you do not know how the callback function works, you can take a look at wrapmany and callback.
El. Model
Jquery. FN. Model
Is a helper tool of jquery. It can return an instance of a model from the HTML element. The list. ejs template converts all tasks into HTML elements, as follows:
<div <%= tasks[i] %>> ... </div>
Remaining Time timeremaining
Timeremaining is just an example function used to encapsulate the raw data in your model.
Other good things
The above is just a small attempt on the model function. Let's take a look at the following features:
Encapsulation
Learn how to interact with services:
$.Model("Task",{ findAll : "/tasks.json", findOne : "/tasks/{id}.json", create : "/tasks.json", update : "/tasks/{id}.json"},{})Type conversion
Convert "10-20-1982" data to new date (1982,9, 20)
$.Model("Task",{ attributes : {birthday : "date"} convert : { date : function(raw){ ... } }},{})Jquery. model. List
Learn how to easily process multiple examples:
$.Model.List.extend("Task.List",{ destroyAll : function(){ var ids = this.map(function(c){ return c.id }); $.post("/destroy", ids, this.callback('destroyed'), 'json') }, destroyed : function(){ this.each(function(){ this.destroyed() }); }}); ".destroyAll click" : function(){ this.find('.destroy:checked') .closest('.task') .models() .destroyAll();}Verify
Verify the attributes of your model
$.Model.extend("Contact",{init : function(){ this.validate("birthday",function(){ if(this.birthday > new Date){ return "your birthday needs to be in the past" } })},{});