`
since1027
  • 浏览: 9109 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

Part 4: CRUD Operations on BackboneJs Models using HTTP REST Service

阅读更多
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:

  • 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/
分享到:
评论

相关推荐

    springmvc入门小项目:CRUD

    在这个"springmvc 入门小项目:CRUD"中,我们将探讨如何使用 SpringMVC 实现基本的数据库操作,即创建(Create)、读取(Read)、更新(Update)和删除(Delete)数据。 1. **SpringMVC 框架基础** - **...

    WCF REST service test

    - **WCFRestService**: 这可能是服务的实现,包含服务接口定义、服务实现类和配置文件。 - **WCFRestServiceTest**: 这是测试客户端,可能包含了发送HTTP请求、解析响应和验证结果的代码。 通过对这两个文件的详细...

    Professional NoSQL 英文版 Shashank.Tiwari

    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 ...

    WCF REST Service Template 40

    安装**WcfRestService40(CS).vsix** 文件后,用户在Visual Studio 2010中就可以直接创建符合RESTful原则的服务,从而提高开发效率。 **WCF REST服务的关键概念:** 1. **服务合同(Service Contract)**:定义了...

    ejemplo_rails_crud:Crud Para Probar Ruby on Rail

    【ejemplo_rails_crud:Crud Para Probar Ruby on Rails】是一个基于Ruby on Rails框架的简单CRUD(创建、读取、更新、删除)应用程序示例。这个项目旨在帮助开发者了解如何在Rails环境下构建基本的数据操作功能。让...

    crud-angular:Crud Angular (Spring Rest + angular)

    标题“crud-angular:Crud Angular (Spring Rest + angular)”和描述“原油示例 Angular Crud(弹簧支架+角度)”提到了一个使用Angular前端框架与Spring后端框架构建的CRUD(创建、读取、更新、删除)应用。...

    rest-server-1.0.0-SNAPSHOT.war

    rest-server-1.0.0-SNAPSHOT.war

    vue-crud:基于Vue.js的REST-ful CRUD系统

    基于Vue.js的REST-ful CRUD系统。 Vue CRUD允许创建用于管理单个表的机制,以及具有登录系统和模块的CMS或扩展CRM。 用Vue CRUD构建的应用程序是SPA(单页应用程序),因此它比基于Wordpress,Joomla等的应用程序...

    distributed-crud-service:crud 服务实现

    本项目"distributed-crud-service"旨在提供一个基于JavaScript的CRUD服务实现,以适应分布式系统的架构需求。 1. 分布式系统基础 分布式系统是由多台独立的计算机通过网络相互连接,共同协作完成一项任务。这种...

    TP_CRUD_Ionic:CRUD_IONIC

    【标题】"TP_CRUD_Ionic:CRUD_IONIC" 指的是一项使用Ionic框架开发CRUD(创建、读取、更新、删除)应用的实战项目。这个项目可能是为了教授开发者如何利用Ionic和TypeScript构建功能完备的移动应用程序。 【描述】...

    crud:Crud C#

    CRUD(Create, Read, Update, Delete)是数据库操作的基础,代表了创建、读取、更新和删除数据的核心功能。在C#编程语言中,CRUD操作通常与ADO.NET、Entity Framework等数据访问技术结合使用,以实现对数据库的数据...

    contact_api:CRUD Flask REST API

    "contact_api:CRUD Flask REST API" 是一个基于Python的Web应用项目,它利用Flask框架构建了一个完整的创建(Create)、读取(Read)、更新(Update)和删除(Delete)操作的RESTful API。REST(Representational ...

    Adm.Web:CRUD示例

    Adm.Web :check_mark_button:CRUD示例 :star:普罗耶托 :alien_monster: Este projetoéum CRUD简单。 实体框架核心。 作为控制器的脚手架。达多斯银行 :large_blue_diamond: 暂无criamostrêstabelas que se ...

    crud-param:CRUD URL 参数

    在IT行业中,CRUD操作是数据库管理的基本概念,代表创建(Create)、读取(Read)、更新(Update)和删除(Delete)数据。这些操作通常与Web应用中的接口设计紧密关联,尤其是在JavaScript环境中。当我们谈论"crud-...

    laravel-crud-generator:Laravel CRUD生成器

    这个Laravel Generator... 将创建具有雄辩关系的模型将使用所有资源创建Controller 将在Bootstrap中创建视图要求Laravel >= 5.5PHP >= 7.1安装1-安装composer require ibex/crud-generator --dev2-发布默认程序包的配置...

    api-crud-nodejs:CRUD API REST-NODE.JS

    CRUD API REST-NODE.JS原始数据存储库是MySQL的基础。 实现node.js的功能,表示COMO框架和Para模板的把手。 先决条件 Node.js MySQL数据库 因特拉尔普罗维克托 当地的无名小卒。 优先保护的保护笛卡儿的资料,编辑...

    CRUD-React-Redux:CRUD - React、Redux Hooks、Rest API 和 Axios 并使用 json-server api 模拟后端

    在本项目中,"CRUD-React-Redux"是一个典型的前端开发示例,它结合了React、Redux Hooks、Rest API以及Axios库,利用json-server作为模拟后端服务。这个项目旨在展示如何在现代Web应用中进行创建(Create)、读取...

    crud_java_spring_rest_api:CRUD使用Java Spring Boot和PostgreSQL

    CRUD Rest API(Java Spring启动) aplikasi rest api dibuat menggunakan javaSpring启动,PostgreSQL get all data method = GET url = localhost:8080/api/tutorials get data data by id method = GET url = ...

    CrudDotNet:CRUD ApiRest和Blazor C#

    CrudDotNet是一个项目,专注于使用C#语言和现代Web技术实现CRUD(创建、读取、更新、删除)操作。这个项目结合了API RESTful服务和Blazor框架,为开发人员提供了一种高效且灵活的方式来构建Web应用程序。下面将详细...

    rest风格+jdbctemplate的CRUD操作.rar

    使用SpringMVC+jdbctemplate实现REST风格的CRUD功能 完成功能:能够对用户进行CRUD操作,界面粗糙,只做演示 运行环境:eclipse2019.03+JDK8+Tomcat9.0.41+MySQL5.5 运用到的技术:spring+springMVC+jdbctemplate+...

Global site tag (gtag.js) - Google Analytics