What is a model?

Across the internet the definition of MVC is so diluted that it's hard to tell what exactly your model should be doing. The authors of backbone.js have quite a clear definition of what they believe the model represents in backbone.js.

Models are the heart of any JavaScript application, containing the interactive data as well as a large part of the logic surrounding it: conversions, validations, computed properties, and access control.

So for the purpose of the tutorial let's create a model.

    Person = Backbone.Model.extend({
initialize: function(){
alert("Welcome to this world");
}
}); var person = new Person;

So initialize() is triggered whenever you create a new instance of a model( models, collections and views work the same way ). You don't have to include it in your model declaration but you will find yourself using it more often than not.

Setting attributes

Now we want to pass some parameters when we create an instance of our model.

    Person = Backbone.Model.extend({
initialize: function(){
alert("Welcome to this world");
}
}); var person = new Person({ name: "Thomas", age: 67});
// or we can set afterwards, these operations are equivelent
var person = new Person();
person.set({ name: "Thomas", age: 67});

So passing a JavaScript object to our constructor is the same as calling model.set(). Now that these models have attributes set we need to be able to retrieve them.

Getting attributes

Using the model.get() method we can access model properties at anytime.

    Person = Backbone.Model.extend({
initialize: function(){
alert("Welcome to this world");
}
}); var person = new Person({ name: "Thomas", age: 67, child: 'Ryan'}); var age = person.get("age"); // 67
var name = person.get("name"); // "Thomas"
var child = person.get("child"); // 'Ryan'

Setting model defaults

Sometimes you will want your model to contain default values. This can easily be accomplished by setting a property name 'defaults' in your model declaration.

    Person = Backbone.Model.extend({
defaults: {
name: 'Fetus',
age: 0,
child: ''
},
initialize: function(){
alert("Welcome to this world");
}
}); var person = new Person({ name: "Thomas", age: 67, child: 'Ryan'}); var age = person.get("age"); // 67
var name = person.get("name"); // "Thomas"
var child = person.get("child"); // 'Ryan'

Manipulating model attributes

Models can contain as many custom methods as you like to manipulate attributes. By default all methods are public.

    Person = Backbone.Model.extend({
defaults: {
name: 'Fetus',
age: 0,
child: ''
},
initialize: function(){
alert("Welcome to this world");
},
adopt: function( newChildsName ){
this.set({ child: newChildsName });
}
}); var person = new Person({ name: "Thomas", age: 67, child: 'Ryan'});
person.adopt('John Resig');
var child = person.get("child"); // 'John Resig'

So we can implement methods to get/set and perform other calculations using attributes from our model at any time.

Listening for changes to the model

Now onto one of the more useful parts of using a library such as backbone. All attributes of a model can have listeners bound to them to detect changes to their values. In our initialize function we are going to bind a function call everytime we change the value of our attribute. In this case if the name of our "person" changes we will alert their new name.

    Person = Backbone.Model.extend({
defaults: {
name: 'Fetus',
age: 0
},
initialize: function(){
alert("Welcome to this world");
this.on("change:name", function(model){
var name = model.get("name"); // 'Stewie Griffin'
alert("Changed my name to " + name );
});
}
}); var person = new Person({ name: "Thomas", age: 67});
person.set({name: 'Stewie Griffin'}); // This triggers a change and will alert()

So we can bind the change listener to individual attributes or if we like simply 'this.on("change", function(model){});' to listen for changes to all attributes of the model.

You might meet with Error :Uncaught TypeError:Object[object object] has no method 'on' . here. this is becasue

You need to update jQuery version.

Because jQuery 1.6 does not have .on() it's added into new version of jQuery.

Interacting with the server

Models are used to represent data from your server and actions you perform on them will be translated to RESTful operations.

The id attribute of a model identifies how to find it on the database usually mapping to the surrogate key.

For the purpose of this tutorial imagine that we have a mysql table called Users with the columns idnameemail.

The server has implemented a RESTful URL /user which allows us to interact with it.

Our model definition shall thus look like;

    var UserModel = Backbone.Model.extend({
urlRoot: '/user',
defaults: {
name: '',
email: ''
} });

Creating a new model

If we wish to create a new user on the server then we will instantiate a new UserModel and call save. If the id attribute of the model is null, Backbone.js will send a POST request to the urlRoot of the server.

    var UserModel = Backbone.Model.extend({
urlRoot: '/user',
defaults: {
name: '',
email: ''
}
});
var user = new Usermodel();
// Notice that we haven't set an `id`
var userDetails = {
name: 'Thomas',
email: 'thomasalwyndavis@gmail.com'
};
// Because we have not set a `id` the server will call
// POST /user with a payload of {name:'Thomas', email: 'thomasalwyndavis@gmail.com'}
// The server should save the data and return a response containing the new `id`
user.save(userDetails, {
success: function (user) {
alert(user.toJSON());
}
})

Our table should now have the values

1, 'Thomas', 'thomasalwyndavis@gmail.com'

Getting a model

Now that we have saved a new user model, we can retrieve it from the server. We know that the id is 1 from the above example.

If we instantiate a model with an id, Backbone.js will automatically perform a get request to the urlRoot + '/id' (conforming to RESTful conventions)

    // Here we have set the `id` of the model
var user = new Usermodel({id: 1}); // The fetch below will perform GET /user/1
// The server should return the id, name and email from the database
user.fetch({
success: function (user) {
alert(user.toJSON());
}
})

Updating a model

Now that we have a model that exist on the server we can perform an update using a PUT request. We will use the save api call which is intelligent and will send a PUT request instead of a POST request if an id is present(conforming to RESTful conventions)

    // Here we have set the `id` of the model
var user = new Usermodel({
id: 1,
name: 'Thomas',
email: 'thomasalwyndavis@gmail.com'
}); // Let's change the name and update the server
// Because there is `id` present, Backbone.js will fire
// PUT /user/1 with a payload of `{name: 'Davis', email: 'thomasalwyndavis@gmail.com'}`
user.save({name: 'Davis'}, {
success: function (model) {
alert(user.toJSON());
}
});

Deleting a model

When a model has an id we know that it exist on the server, so if we wish to remove it from the server we can call destroydestroy will fire off a DELETE /user/id (conforming to RESTful conventions).

    // Here we have set the `id` of the model
var user = new Usermodel({
id: 1,
name: 'Thomas',
email: 'thomasalwyndavis@gmail.com'
}); // Because there is `id` present, Backbone.js will fire
// DELETE /user/1
user.destroy({
success: function () {
alert('Destroyed');
}
});

Tips and Tricks

Get all the current attributes


var person = new Person({ name: "Thomas", age: 67});
var attributes = person.toJSON(); // { name: "Thomas", age: 67}
/* This simply returns a copy of the current attributes. */ var attributes = person.attributes;
/* The line above gives a direct reference to the attributes and you should be careful when playing with it. Best practise would suggest that you use .set() to edit attributes of a model to take advantage of backbone listeners. */

Validate data before you set or save it

    Person = Backbone.Model.extend({
// If you return a string from the validate function,
// Backbone will throw an error
validate: function( attributes ){
if( attributes.age < 0 && attributes.name != "Dr Manhatten" ){
return "You can't be negative years old";
}
},
initialize: function(){
alert("Welcome to this world");
this.bind("error", function(model, error){
// We have received an error, log it, alert it or forget it :)
alert( error );
});
}
}); var person = new Person;
person.set({ name: "Mary Poppins", age: -1 });
// Will trigger an alert outputting the error var person = new Person;
person.set({ name: "Dr Manhatten", age: -1 });
// God have mercy on our souls

Tutorial: Model的更多相关文章

  1. Struts2 OGNL使用详解(转)

    OGNL OGNL ( Object Graph Navigation Language ),对象图导航语言.这是一种强大的表达式语言,通过它可以非常方便的来操作对象属性. 在 Struts2 中,O ...

  2. Maven+SpringMVC+SpringFox+Swagger整合示例

    查考链接:https://my.oschina.net/wangmengjun/blog/907679 coding地址:https://git.coding.net/conding_hjy/Spri ...

  3. 一步步完成Maven+SpringMVC+SpringFox+Swagger整合示例

    本文给出一个整合Maven+SpringMVC+SpringFOX+Swagger的示例,并且一步步给出完成步骤. 本人在做实例时发现 http://blog.csdn.net/zth1002/art ...

  4. ngxs 状态管理器

    官网文档 ng6,rxjs6.0.0,ngxs3.0.1 λ ng new ngxs --style=styl --routing --skip-install λ cd ngxs λ yarn λ ...

  5. 高级数据库及一步一步搭建versant数据库

    总的来说,高级数据库课程分为分布式数据库和面向对象数据库两块.分布式数据库介绍了分布式数据库的方方面面,包括数据库系统的设计.查询处理优化.事务管理和恢复.并发控制.可靠性.安全性与目录管理等.面向对 ...

  6. Anaconda+django写出第一个web app(二)

    今天开始建立App中的第一个Model,命名为Tutorial. Model的定义在main文件夹下的models.py中通过类进行,我们希望Tutorial这个model包含三个属性:标题.内容和发 ...

  7. Anaconda+django写出第一个web app(一)

    在安装好Anaconda和django之后,我们就可以开始创建自己的第一个Web app,那么首先创建一个空文件夹,之后创建的文件都在这个文件夹内. 启动命令行进入此文件夹内,可以先通过如下命令查看一 ...

  8. caffe2 教程入门(python版)

    学习思路 1.先看官方文档,学习如何使用python调用caffe2包,包括 Basics of Caffe2 - Workspaces, Operators, and Nets Toy Regres ...

  9. SpringMVC、SpringFox和Swagger整合项目实例

    目标 在做项目的时候,有时候需要提供其它平台(如业务平台)相关的HTTP接口,业务平台则通过开放的HTTP接口获取相关的内容,并完成自身业务~ 提供对外开放HTTP API接口,比较常用的是采用Spr ...

随机推荐

  1. node笔记——gulp修改静态文件的名字

    cmd小技巧: 1.换到下级或同等级目录 D: 2.换到上级目录 cd.. node 包管理器小技巧[以gulp为例] npm install --save-dev gulp gulp-concat ...

  2. 《HTML5与CSS3基础教程》学习笔记 ——Four Day

    第十六章 1.    输入和元素 电子邮件框 <input type="email"> 搜索框 <input type="search"> ...

  3. Codevs 1003 电话连线

    时间限制: 1 s   空间限制: 128000 K   题目等级 : 黄金 Gold 题目描述 Description 一个国家有n个城市.若干个城市之间有电话线连接,现在要增加m条电话线(电话线当 ...

  4. c/c++面试总结(2)

    4.深拷贝和浅拷贝 (1)什么时候会用到拷贝函数 一个对象以值传递的方式传入函数(就是作为入参) 一个对象以值传递的方式从函数返回(就是作为返回值) 一个对象需要通过另外一个对象进行初始化 (2)是否 ...

  5. void指针

    指针有两个属性:指向变量/对象的地址 和长度 但是指针只存储地址,长度则取决于指针的类型 编译器根据指针的类型从指针指向的地址向后寻址 指针类型不同则寻址范围也不同,比如: int*从指定地址向后寻找 ...

  6. MD5加密方式

    MD5加密是一种安全系数比较高的加密方式,具有不可逆的加密特征,就是很难进行破解,现在对MD5加密进行破解的方式还是采用跑数据库的方式,时间比较长,耗费性能比较大,所以一般的破解都是要收费的. C#中 ...

  7. OC 内存管理机制总结

    OC 内存管理机制总结 一:OC内存管理机制目前分为两块,其一自动内存管理机制,其二手动内存管理机制: 1.首先我们从自动内存管理机制讲起: 1)什么是自动内存管理机制,自动内存管理机制就是程序中所创 ...

  8. C# 枚举操作扩展类

    using System; using System.Linq; using System.ComponentModel; namespace Demo.Common { /// <summar ...

  9. jquery.tmpl.min.js--前端实现模版--数据绑定--详解

    动态请求数据来更新页面是现在非常常用的方法,比如博客评论的分页动态加载,微博的滚动加载和定时请求加载等. 这些情况下,动态请求返回的数据一般不是已拼好的 HTML 就是 JSON 或 XML,总之不在 ...

  10. Cassandra1.2文档学习解读计划——为自己鼓劲

    最近想深入研究一下Cassandra,而Cassandra没有中文文档,仅有的一些参考书都是0.7/0.6版本的.因此有个计划,一边学习文档(地址:http://www.datastax.com/do ...