- 浏览: 7832 次
- 性别:
- 来自: 南京
最新评论
-
since1027:
Backbone系列教程的最后一章了,希望对Backbone入 ...
Part 8: Understanding Backbone.js Events
Part 4: CRUD Operations on BackboneJs Models using HTTP REST Service
- 博客分类:
- Backbone
In this article we will discuss how we can perform CRUD operations on a backbone model using a REST based HTTP service.
Background
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:
Using the code
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:
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:
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:
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.
Now let us try to perform CRUD operations on this model.
Create
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.
Read
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.
Update
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.
Delete
Now to delete a Model, we just need to call the destroy method of the model object.
Custom URLs to perform CRUD operation on models
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.
Now we can perform the CRUD operations on this model in the same way as we did for the previous model.
Point of interest
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.
原文链接:http://rahulrajatsingh.com/2014/07/backbone-tutorial-part-4-crud-operations-on-backbonejs-models-using-http-rest-service/
Background
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:
- Part 1: Introduction to Backbone.Js
- Part 2: Understanding the basics of Backbone Models
- Part 3: More about Backbone Models
- Part 4: CRUD Operations on BackboneJs Models using HTTP REST Service
- Part 5: Understanding Backbone.js Collections
- Part 6: Understanding Backbone.js Views
- Part 7: Understanding Backbone.js Routes and History
- Part 8: Understanding Backbone.js Events
Using the code
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:
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:
- Create: POST http://localhost:51377/api/values
- Read: GET http://localhost:51377/api/values/{id}
- Update: PUT http://localhost:51377/api/values/{id}
- Delete: DELETE http://localhost:51377/api/values/{id}
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.
Create
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"); } });
Read
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")); } });
Update
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"); } }); } });
Delete
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"); } });
Custom URLs to perform CRUD operation on models
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.
Point of interest
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.
原文链接:http://rahulrajatsingh.com/2014/07/backbone-tutorial-part-4-crud-operations-on-backbonejs-models-using-http-rest-service/
- backboneSample.zip (127.7 KB)
- 下载次数: 0
- WebAPISample.zip (3.1 MB)
- 下载次数: 0
发表评论
-
Part 8: Understanding Backbone.js Events
2016-06-22 10:34 774In this article, we will look a ... -
Part 7: Understanding Backbone.js Routes and History
2016-06-22 09:52 485In this article, we will try to ... -
Part 6: Understanding Backbone.js Views
2016-06-22 09:50 610In this article, we will try to ... -
Part 5: Understanding Backbone.js Collections
2016-06-21 14:39 568In this article we will discuss ... -
Part 3: More about Backbone Models
2016-06-21 14:08 655In this article we will look at ... -
Part 2: Understanding the basics of Backbone Models
2016-06-21 12:55 529When we talk about any MV* patt ... -
Part 1: Introduction to Backbone.Js
2016-06-21 11:12 675It was a long time ago (almost ...
相关推荐
springmvc入门小项目:CRUD
CHAPTER 4: UNDERSTANDING THE STORAGE ARCHITECTURE 73 CHAPTER 5: PERFORMING CRUD OPERATIONS 97 CHAPTER 6: QUERYING NOSQL STORES 117 CHAPTER 7: MODIFYING DATA STORES AND MANAGING EVOLUTION 137 ...
contact_api:CRUD Flask REST API
Java Simple Banking System CRUD Operations.zip
CRUD_WinForm:CRUD Basico de Windows窗体
rest-server-1.0.0-SNAPSHOT.war
Angular_Node_Express_MongoDB_CRUD:CRUD
Symfony_Crud_Doctrine_Form:CRUD原理和形式
blautecUusarios项目:CRUD USUARIOS USANDO FIREBASE MONGODB SPRING BOOT API REST
NULL 博文链接:https://mvplee.iteye.com/blog/2186235
crud-operation-firebase-realtime-db-javascript:Crud操作
基于Vue.js的REST-ful CRUD系统。 Vue CRUD允许创建用于管理单个表的机制,以及具有登录系统和模块的CMS或扩展CRM。 用Vue CRUD构建的应用程序是SPA(单页应用程序),因此它比基于Wordpress,Joomla等的应用程序...
Challenger-reactjs-crud:CRUD没有ReactJS
ReactAppCrud:Crud用户注册
TP_CRUD_Ionic:CRUD_IONIC
nodejs-crud:Crud Node.js Express MongoDB
Adm.Web :check_mark_button:CRUD示例 :star:普罗耶托 :alien_monster: Este projetoéum CRUD简单。 实体框架核心。 作为控制器的脚手架。达多斯银行 :large_blue_diamond: 暂无criamostrêstabelas que se ...
这个Laravel Generator... 将创建具有雄辩关系的模型将使用所有资源创建Controller 将在Bootstrap中创建视图要求Laravel >= 5.5PHP >= 7.1安装1-安装composer require ibex/crud-generator --dev2-发布默认程序包的配置...
粗鲁的 Crud C# Primeiro Crud em C#para estudo Estudar
Crud-avance-ecommerce:Crud 4 Capas usando SP和ademasse estasandando实体框架