Part 4: CRUD Operations on BackboneJs Models using HTTP REST Service-程序员宅基地

技术标签: Backbone  ViewUI  backnone  mvc  javascript  

In this article we will discuss how we can perform CRUD operations on a backbone model using a REST based HTTP service.

[size=large][b]Background[/b][/size]

Earlier we have discussed about the benefits of using backbone.js and we also looked at the backbone models.

In this article we will look at performing the CRUD operations on backbone models using a REST based web service.

Link to complete series:

[list]
[*][url=http://since1027.iteye.com/blog/2306301]Part 1: Introduction to Backbone.Js[/url]
[*][url=http://since1027.iteye.com/blog/2306311]Part 2: Understanding the basics of Backbone Models[/url]
[*][url=http://since1027.iteye.com/blog/2306332]Part 3: More about Backbone Models[/url]
[*][url=http://since1027.iteye.com/blog/2306344]Part 4: CRUD Operations on BackboneJs Models using HTTP REST Service[/url]
[*][url=http://since1027.iteye.com/blog/2306346]Part 5: Understanding Backbone.js Collections[/url]
[*][url=http://since1027.iteye.com/blog/2306355]Part 6: Understanding Backbone.js Views[/url]
[*][url=http://since1027.iteye.com/blog/2306361]Part 7: Understanding Backbone.js Routes and History[/url]
[*][url=http://since1027.iteye.com/blog/2306566]Part 8: Understanding Backbone.js Events[/url]
[/list]
[color=brown][size=large][b]Using the code[/b][/size][/color]

The first thing we will do is that we will create a simple REST based web api that can be used to save the data on the server using our simple backbone application. For this I have created a simple database with a single table as:

[img]http://i1.wp.com/rahulrajatsingh.com/wp-content/uploads/2014/07/DB.jpg?w=284[/img]

The ID field is configured to auto increment and this is the primary key of the table. so while creating a new model we don’t have to provide this to the server. Now on top of this model, I have written a simple ASP.NET web api that will provide us the RESTful api. This API is configured to run on my local machine at: http://localhost:51377/. The API details are as follows:

[list]
[*][b]Create:[/b] POST http://localhost:51377/api/values
[*][b]Read:[/b] GET http://localhost:51377/api/values/{id}
[*][b]Update:[/b] PUT http://localhost:51377/api/values/{id}
[*][b]Delete:[/b] DELETE http://localhost:51377/api/values/{id}
[/list]
Once we have the API running, we can start working on our backbone model. We had create the backbone model in our previous article as:

var Book = Backbone.Model.extend({
   
defaults: {
ID: "",
BookName: ""
},
idAttribute: "ID",
initialize: function () {
console.log('Book has been initialized');
this.on("invalid", function (model, error) {
console.log("Houston, we have a problem: " + error)
});
},
constructor: function (attributes, options) {
console.log('Book\'s constructor had been called');
Backbone.Model.apply(this, arguments);
},
validate: function (attr) {
if (!attr.BookName) {
return "Invalid BookName supplied."
}
}
});

The backbone models inherently supports saving on the server using a restful web api. To save the model using a HTTP REST service, we need to specify the urlRoot in the backbone model. To actually save the model, we can call the save on the backbone model.The save method will trigger the validations and if the validations are successful, it will try to identify the action to be performed i.e. create or update and based on that action, it will use urlRoot and call the appropriate REST API to perform the operation. Let us specify the URL root to enable this model to use our web api service.

var Book = Backbone.Model.extend({
   
defaults: {
ID: "",
BookName: ""
},
idAttribute: "ID",
initialize: function () {
console.log('Book has been initialized');
this.on("invalid", function (model, error) {
console.log("Houston, we have a problem: " + error)
});
},
constructor: function (attributes, options) {
console.log('Book\'s constructor had been called');
Backbone.Model.apply(this, arguments);
},
validate: function (attr) {
if (!attr.BookName) {
return "Invalid BookName supplied."
}
},
urlRoot: 'http://localhost:51377/api/Books'
});

Now let us try to perform CRUD operations on this model.

[size=large][b]Create[/b][/size]

To create a new entity on the server, we need to populate the non identity fields in the model (other than ID in this case) and then call the Save method on the model.

// Lets perform a create operation [CREATE]
var book = new Book({ BookName: "Backbone Book 43" });
book.save({}, {
success: function (model, respose, options) {
console.log("The model has been saved to the server");
},
error: function (model, xhr, options) {
console.log("Something went wrong while saving the model");
}
});

[size=large][b]Read
[/b][/size]
To read a single book entity, we need to create the book entity with the identity attribute populated, i.e., the ID of the book we want to read. Then we need to call the fetch method on the model object.

// Now let us try to retrieve a book [READ]
var book1 = new Book({ ID: 40 });
book1.fetch({
success: function (bookResponse) {
console.log("Found the book: " + bookResponse.get("BookName"));
}
});

[size=large][b]Update[/b][/size]

Now let’s say we want to update the name of the book retrieved in the earlier fetch call. All we need to do is set the attributes we need to update and call the save method again.

// Lets try to update a book [UPDATE]
var book1 = new Book({ ID: 40 });
book1.fetch({
success: function (bookResponse) {
console.log("Found the book: " + bookResponse.get("BookName"));
// Let us update this retreived book now (doing it in the callback) [UPDATE]
bookResponse.set("BookName", bookResponse.get("BookName") + "_updated");
bookResponse.save({}, {
success: function (model, respose, options) {
console.log("The model has been updated to the server");
},
error: function (model, xhr, options) {
console.log("Something went wrong while updating the model");
}
});
}
});

[size=large][b]Delete[/b][/size]

Now to delete a Model, we just need to call the destroy method of the model object.

// Let us delete the model with id 13 [DELETE]
var book2 = new Book({ ID: 40 });
book2.destroy({
success: function (model, respose, options) {
console.log("The model has deleted the server");
},
error: function (model, xhr, options) {
console.log("Something went wrong while deleting the model");
}
});

[size=large][b]Custom URLs to perform CRUD operation on models[/b][/size]

There are few scenarios where we might want to have provide custom URLs for the individual operations. This can be achieved by overriding the sync function and providing custom URL for each action. Let us create one more model BookEx to see how this can be done.

var BookEx = Backbone.Model.extend({
   
defaults: {
ID: "",
BookName: ""
},
idAttribute: "ID",

// Lets create function which will return the custom URL based on the method type
getCustomUrl: function (method) {
switch (method) {
case 'read':
return 'http://localhost:51377/api/Books/' + this.id;
break;
case 'create':
return 'http://localhost:51377/api/Books';
break;
case 'update':
return 'http://localhost:51377/api/Books/' + this.id;
break;
case 'delete':
return 'http://localhost:51377/api/Books/' + this.id;
break;
}
},
// Now lets override the sync function to use our custom URLs
sync: function (method, model, options) {
options || (options = {});
options.url = this.getCustomUrl(method.toLowerCase());

// Lets notify backbone to use our URLs and do follow default course
return Backbone.sync.apply(this, arguments);
}
});

Now we can perform the CRUD operations on this model in the same way as we did for the previous model.

[size=large][b]Point of interest[/b][/size]

In this article we have looked at how to perform CRUD operations on backbone models using HTTP based REST service. This has been written from a beginner’s perspective. I hope this has been informative.

原文链接:[url]http://rahulrajatsingh.com/2014/07/backbone-tutorial-part-4-crud-operations-on-backbonejs-models-using-http-rest-service/[/url]
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/zlxznu/article/details/84807120

智能推荐

有了这个开源项目,再也不怕去BAT和字节跳动面试考算法了-程序员宅基地

文章浏览阅读1.1k次。热文导读|点击标题阅读互联网寒冬下,程序员如何突围提升自己?已有 Android 项目集成 Flutter 寻坑记“37岁,年薪50万,一夜被裁”:伪上班,毁掉了多..._字节跳动java开源项目

SQL语句中on 、where 和 having的区别_having on语句-程序员宅基地

文章浏览阅读2k次,点赞2次,收藏8次。关键字: on数据库在通过连接两张或多张表来返回记录时,都会生成一张中间的临时表,然后再将这张临时表返回给用户。在使用left jion时,on和where条件的区别如下:1、 on条件是在生成临时表时使用的条件,它不管on中的条件是否为真,都会返回左边表中的记录。2、where条件是在临时表生成好后,再对临时表进行过滤的条件。这时已经没有left join的含义(必须返回左边表的..._having on语句

格林公式计算多边形的面积_格林公式求多边形面积-程序员宅基地

文章浏览阅读1.1w次,点赞6次,收藏27次。算法导论第31章第一节第8题。只要是边不相交的简单多边形,也就是说,不仅凸多边形,还有各种奇形怪状的凹多边形,都可以用格林公式求出面积。格林公式:若函数P(x,y), Q(x,y)在由一条或几条光滑曲线所围成的闭区域D上连续,且有连续的一阶偏导数,则有L为区域D的边界曲线,并取正方向。边不相交的简单多边形正好是由数条线段围成的闭区域,所以可以使用格林公式。令P=0, Q=x,则面积S = 设第i个..._格林公式求多边形面积

什么是nvm,nvm详解-程序员宅基地

文章浏览阅读9.5k次,点赞3次,收藏3次。nvm1. 概念详情点击nvm全名node.js version management,是一个node的版本管理工具首先最重要的是:一定要卸载已安装的 NodeJS,否则会发生冲突。然后下载 nvm-windows 最新安装包,直接安装即可。_nvm

软件测试影响最深的bug,软件测试面试题-那些让我印象深刻的bug-程序员宅基地

文章浏览阅读7.7k次。相信大家在工作中面试过程中经常被问到,让你印象最深刻的一个bug是什么,这是一个开放性的题目,并没有标准答案,每个人接触过的系统都不一样,遇到过的问题也不一样,可能面试官只是想看一下你的表达能力,以及平常在工作中是否会进行总结。这类问题可以挑选容易被人忽略的场景,难以想到的场景,特殊机型的兼容性或者特殊操作下才会出现的问题等。接下来为大家分享一个我今天遇到的一个问题:由于缓存中key的设置不合理导..._面试过程中遇到你印象最深刻的bug 是什么

ActivityManagerService启动activity流程简析(二)_removepausetimeout-程序员宅基地

文章浏览阅读2.7k次。Task.java private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) { ... // 1.获取栈顶的activity ActivityRecord next = topRunningActivity(true /* focusableOnly */); ... ..._removepausetimeout

随便推点

【ubuntu】16.04搭建DNS服务器_ubuntu16.04搭建dns内网服务器-程序员宅基地

文章浏览阅读482次。1.更新环境apt-get update2.安装bind9apt install bind93.配置/etc/bind/named.conf 文件(服务器域解析文件),其中Router.com、TestIpsec.com是需要解析的域名zone "Router.com"{ type master;file "db.Router.com";};zone "TestIpsec.com"{ type master;file "db.TestIpsec.com";};4._ubuntu16.04搭建dns内网服务器

创建数组对象_ets定义数组-程序员宅基地

文章浏览阅读1.8k次。开发工具与关键技术:VS、创建数组对象作者:陆桂超撰写时间:2019年7月27日1、 如下图所示是一个动态添加的table表格,这里显示有三条数据。那么如何把这三条数据传到控制器呢?我们可以把这三条数据封装到一个数组里面,然后把数组传到控制器。2、首先在for循环外面声明一个数组,记住不能在for循环里面声明数组,因为如果在for循环里面声明数组,这样就每循环一次都会创建一个数组,而我们..._ets定义数组

MyBatis--1_mybatis indexof(',')==1-程序员宅基地

文章浏览阅读103次。概述MyBatisMyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。以开发sql语句的工作量为代价换取高灵活性##Hello MyBatis1、添加依赖<dependency> _mybatis indexof(',')==1

gperftools使用说明_gperftools使用详解-程序员宅基地

文章浏览阅读1.9k次。原文章:使用gperftool + libuwind + graphviz来分析程序性能为了了解程序的执行时间以及各个函数之间的调用关系,可以通过Google的gperftool来统计函数之间的关系以及时间信息。通过分析每个函数的时间信息,就可以看程序的关键消耗点在什么地方。1. 安装gperftools:http://code.google.com/p/gperftools/do_gperftools使用详解

PHP 常用函数(一)-程序员宅基地

文章浏览阅读101次。12个常用数学函数函数名描述实例输入输出abs()求绝对值$abs = abs(-4.2); //4.2数字绝对值数字ceil()进一法取整echo ceil(9.999); // 10浮点数进一取整floor()舍去法取整echo floor(9.999); // 9浮点数直接舍去小数部分fmod()浮点数取余x=5.7;...

android ui 特效_leonids安卓-程序员宅基地

文章浏览阅读346次。http://blog.csdn.net/lmj623565791/article/details/46858663https://github.com/hongyangAndroid/Android_Blog_Demos_leonids安卓

推荐文章

热门文章

相关标签