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

Part 3: More about Backbone Models

阅读更多
In this article we will look at some more concepts related to backbone models. We will try to see how we can override the default model behavior. We will look at the signification of model IDs, how we can validate a model and finally how a model can be persisted either locally or on a server.

Link to complete series:


The Initialize function and the Constructor

Whenever we create a model, the backbone will call its initialize function. We can override this function to provide custom behavior to it.

var Book = Backbone.Model.extend({
    defaults: {
        ID: "",
        BookName: ""
    },
    initialize: function () {
        console.log('Book has been intialized');       
    },
});


So when we create this object the output will be:



Internally what happens is that whenever a backbone model is created, its constructor gets called. The constructor will call the initialize function. It is also possible to provide out own constructor and provide the custom behavior.

var Book = Backbone.Model.extend({
    defaults: {
        ID: "",
        BookName: ""
    },
    initialize: function () {
        console.log('Book has been intialized');       
    },
    constructor: function (attributes, options) {
        console.log('Book\'s constructor had been called');
    },
});

The output when creating this model:



Now the problem with this constructor is that whenever the backbone model is getting created our constructor will be called. But the default constructor also does a lot of other activities at the time of object construction like calling the initialize function. So to make sure that our custom constructor works in unison with all that default behavior we need to let the backbone framework know that we still wants that default behavior. This can be done by calling Backbone.Model.apply(this, arguments); at the end of our custom constructor. This will make sure that our custom constructor will be called and then all the other activities that the default constructor is supposed to do are also done.

var Book = Backbone.Model.extend({
    defaults: {
        ID: "",
        BookName: ""
    },
    initialize: function () {
        console.log('Book has been intialized');       
    },
    constructor: function (attributes, options) {
        console.log('Book\'s constructor had been called');
        Backbone.Model.apply(this, arguments);
    },
});

Now the output will be:



Note: For most of practical purposes overriding the initialize function will suffice. There is seldom a need to override the constructor but in case one decide to override the constructor, this should be the way to do it.

Model identifiers – id, cid and idAttribute

Every model needs to be uniquely identified. For this backbone gives us the model identifiers. The first one to look at is the cid. The cid or the client id is the auto-generated by backbone so that every model can be uniquely identified on the client.

var book1 = new Book();
var book2 = new Book();



Backbone also provides an identifier id to uniquely identify the model entity. This is the id that will be used to identify the model when the model data is actually being synced with server i.e. getting persisted. the cid is more useful for debugging purpose but the id attribute will determine the uniqueness of the model when it comes to CRUD operations on the model. Its fairly straight forward to set and get the id property.

var book2 = new Book();
book2.id = 3;
console.log(book2.id);

Output for the above code will be: 3.

Now it gets a little confusing at this point. Since most of our models will have an attribute that will correspond to the primary key/unique identifier of the entity. Do we need to explicitly set the id value to that attribute. The answer if yes and no. We have to somehow indicate the backbone model what attribute should be used as id but we don’t have to set the id explicitly. we can use the idAttribute to accomplish this.

var Book = Backbone.Model.extend({
    defaults: {
        ID: "",
        BookName: ""
    },
    idAttribute: "ID",
    initialize: function () {
        console.log('Book has been intialized');
    },
    constructor: function (attributes, options) {
        console.log('Book\'s constructor had been called');
        Backbone.Model.apply(this, arguments);
    },
});


Now in the above code we have specified that the ID should be used as id by specifying the idAttribute. Lets try to create a new model with ID value now.

var book3 = new Book({ ID: 43 });
console.log(book1.id);

And we can see that the id value is taken from the specified attribute.



and thus this makes it very easier for the backbone models to work with server side entities and makes the model identification seamless.

Validating the model

When we are working on business applications it is often required that we validate the model before persisting the data. Backbone provides a very easy way of validating the model data. We just need to implement the models validate function.

var Book = Backbone.Model.extend({
    defaults: {
        ID: "",
        BookName: ""
    },
    idAttribute: "ID",
    initialize: function () {
        console.log('Book has been intialized');
    },
    constructor: function (attributes, options) {
        console.log('Book\'s constructor had been called');
        Backbone.Model.apply(this, arguments);
    },
    validate: function (attr) {
        if (attr.ID <= 0) {
            return "Invalid value for ID supplied."
        }
    }
});

What happens here is that whenever we try to save the model(which we will see in next section), the Validate function will get called. It will check the custom
validation logic that we have put in place and validate the model. To test the validate method, we can use models isValid function.

var book4 = new Book({ ID: -4 });
var result = book4.isValid(); // false

Another way to prevent the invalid values in the model attributes is by passing the validate:true while setting the models attribute. This will also trigger the validate function

var book5 = new Book();
book5.set("ID", -1, {validate:true});

What this will do is that this will not even allow setting of invalid values if the value that we are trying to set is invalid as per our custom logic.

How this validation works is that whenever the user chooses to save the model, the validate function will be called. if there is any validation error then the model save will fail. alternatively, the user can choose to pass validate:true whenever he want to restrict the setting of invalid values in the model attributes.

If we want to check the validity of the model at any particular instance, we can use the isValid function to test this. Having said that one important thing to know here is that whenever our validation function fails to validate the model an event invalid is raised by backbone. If we want to listen to this event, we can subscribe to this.

Lets try to hook up to this event and see the validation errors. We will do this in the initialize function of the model.

var Book = Backbone.Model.extend({
    defaults: {
        ID: "",
        BookName: ""
    },
    idAttribute: "ID",
    initialize: function () {
        console.log('Book has been intialized');
        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.ID <= 0) {
            return "Invalid value for ID supplied."
        }
    }
});




Saving the model

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.

So if I have a service running on my local machine, i first need to specify the urlRoot for the service in my model.

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.ID <= 0) {
            return "Invalid value for ID supplied."
        }
    },
    urlRoot: 'http://localhost:51377/api/Books'
});

and to save this model using this service, I could do something like:

var book = new Book({ BookName: "Backbone Book 43" });
    book.save({}, {
        success: function (model, response, 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");
        }
    });

The save function also accepts success and error callback functions so that appropriate action can be taken based on the response from the server.

Now if we want to save the model on local storage rather than on a server, we just need to keep in mind that save function actually calls sync function to actually save/retrieve the model information. So if we need to save the model on a local storage, we need to override the sync function and provide the custom code to save on local storage.

Note: The code shown above(for save model) is syntactically correct but it will not work unless we have a REST service running at mentioned urlRoot. In coming articles, I will explain the model save using the REST service in details along with the sample service and HTML code.

Point of interest

So we saw a few more details about the backbone models. We have not yet looked at how to save the model either locally or via using a service. Perhaps in my next articles, we will talk about that only.

原文链接:http://rahulrajatsingh.com/2014/07/backbone-tutorial-part-3-more-about-backbone-models/
分享到:
评论

相关推荐

    计算机二级公共基础知识模 拟试题及答案详解.pdf

    计算机二级公共基础知识模 拟试题及答案详解.pdf

    电子工程领域的语音发射机电路设计与实现

    内容概要:本文档详细介绍了语音发射机的设计与实现,涵盖了从硬件电路到具体元件的选择和连接方式。文档提供了详细的电路图,包括电源管理、信号处理、音频输入输出接口以及射频模块等关键部分。此外,还展示了各个引脚的功能定义及其与其他组件的连接关系,确保了系统的稳定性和高效性能。通过这份文档,读者可以全面了解语音发射机的工作原理和技术细节。 适合人群:对电子工程感兴趣的初学者、从事嵌入式系统开发的技术人员以及需要深入了解语音发射机制的专业人士。 使用场景及目标:适用于希望构建自己的语音发射设备的研究人员或爱好者,帮助他们掌握相关技术和实际操作技能。同时,也为教学机构提供了一个很好的案例研究材料。 其他说明:文档不仅限于理论讲解,还包括具体的实施步骤,使读者能够动手实践并验证所学知识。

    易语言注册机源码详解:单线程架构下的接码、滑块验证与IP代理实现

    内容概要:本文详细介绍了用易语言编写的单线程全功能注册机源码,涵盖了接码平台对接、滑块验证处理、IP代理管理以及料子导入等多个核心功能。文章首先展示了主框架的初始化配置和事件驱动逻辑,随后深入探讨了接码平台(如打码兔)的API调用及其返回数据的处理方法。对于滑块验证部分,作者分享了如何利用易语言的绘图功能模拟真实用户的操作轨迹,并提高了验证通过率。IP代理模块则实现了智能切换策略,确保代理的有效性和稳定性。此外,料子导入功能支持多种格式的数据解析和去重校验,防止脏数据污染。最后,文章提到了状态机设计用于控制注册流程的状态持久化。 适合人群:有一定编程基础,尤其是熟悉易语言的开发者和技术爱好者。 使用场景及目标:适用于希望深入了解易语言注册机开发的技术细节,掌握接码、滑块验证、IP代理等关键技术的应用场景。目标是帮助读者理解并优化现有注册机的功能,提高其稳定性和效率。 其他说明:文中提到的部分技术和实现方式可能存在一定的风险,请谨慎使用。同时,建议读者在合法合规的前提下进行相关开发和测试。

    计算机绘图实用教程 第三章.pdf

    计算机绘图实用教程 第三章.pdf

    计算机辅助设计—AutoCAD 2018中文版基础教程 各章CAD图纸及相关说明汇总.pdf

    计算机辅助设计—AutoCAD 2018中文版基础教程 各章CAD图纸及相关说明汇总.pdf

    计算机类电子书集合PDF

    C++相关书籍,计算机相关书籍,linux相关及http等计算机学习、面试书籍。

    计算机二级mysql数据库程序设计练习题(一).pdf

    计算机二级mysql数据库程序设计练习题(一).pdf

    计算机发展史.pdf

    计算机发展史.pdf

    计算机二级课件.pdf

    计算机二级课件.pdf

    计算机概论第三讲:计算机组成.pdf

    计算机概论第三讲:计算机组成.pdf

    端侧算力网络白皮书:6G时代终端算力资源高效利用与应用场景解析

    内容概要:本文档由中国移动通信集团终端有限公司、北京邮电大学、中国信息通信研究院和中国通信学会共同发布,旨在探讨端侧算力网络(TCAN)的概念、架构、关键技术及其应用场景。文中详细分析了终端的发展现状、基本特征和发展趋势,阐述了端侧算力网络的定义、体系架构、功能架构及其主要特征。端侧算力网络通过整合海量泛在异构终端的算力资源,实现分布式多级端侧算力资源的高效利用,提升网络整体资源利用率和服务质量。关键技术涵盖层次化端算力感知图模型、资源虚拟化、数据压缩、多粒度多层次算力调度、现场级AI推理和算力定价机制。此外,还探讨了端侧算力网络在智能家居、智能医疗、车联网、智慧教育和智慧农业等领域的潜在应用场景。 适合人群:从事通信网络、物联网、边缘计算等领域研究和开发的专业人士,以及对6G网络和端侧算力网络感兴趣的学者和从业者。 使用场景及目标:适用于希望深入了解端侧算力网络技术原理、架构设计和应用场景的读者。目标是帮助读者掌握端侧算力网络的核心技术,理解其在不同行业的应用潜力,推动端侧算力网络技术的商业化和产业化。 其他说明:本文档不仅提供了端侧算力网络的技术细节,还对其隐私与安全进行了深入探讨

    学习java的心得体会.docx

    学习java的心得体会.docx

    计算机二级考试(南开100题齐全).pdf

    计算机二级考试(南开100题齐全).pdf

    计算机二级C语言考试通关宝典:全面解析核心知识点与解题技巧

    内容概要:本文详细介绍了计算机二级C语言考试的内容和备考方法。首先概述了计算机二级考试的意义及其在计算机技能认证中的重要性,重点讲解了C语言的基础语法,包括程序结构、数据类型、运算符和表达式等。接着深入探讨了进阶知识,如函数、数组、指针、结构体和共用体的应用。最后分享了针对选择题、填空题和编程题的具体解题技巧,强调了复习方法和实战演练的重要性。 适合人群:准备参加计算机二级C语言考试的学生和技术爱好者。 使用场景及目标:①帮助考生系统地掌握C语言的核心知识点;②提供有效的解题策略,提高应试能力;③指导考生制定合理的复习计划,增强实战经验。 其他说明:本文不仅涵盖了理论知识,还提供了大量实例代码和详细的解释,有助于读者更好地理解和应用所学内容。此外,文中提到的解题技巧和复习建议对实际编程也有很大帮助。

    论文格式及要求.doc

    论文格式及要求.doc

    三菱FX3U与台达变频器RS485通信程序设置及应用实例

    内容概要:本文详细介绍了如何使用三菱FX3U PLC及其485BD通信板与四台台达VFD-M系列变频器进行通信的设置与应用。主要内容涵盖硬件连接注意事项、通信参数配置、RS指令的应用、CRC校验算法的实现以及频率给定和状态读取的具体方法。文中提供了多个实用的编程示例,展示了如何通过梯形图和结构化文本编写通信程序,并讨论了常见的调试技巧和优化建议。此外,还提到了系统的扩展性和稳定性措施,如增加温度传感器通信功能和应对电磁干扰的方法。 适合人群:从事工业自动化领域的工程师和技术人员,尤其是那些熟悉三菱PLC和台达变频器的使用者。 使用场景及目标:适用于需要实现多台变频器联动控制的工业应用场景,旨在提高生产效率和系统可靠性。通过学习本文,读者可以掌握如何构建稳定的RS485通信网络,确保变频器之间的高效协同工作。 其他说明:本文不仅提供了详细的理论指导,还包括了许多来自实际项目的经验教训,帮助读者避免常见错误并提升编程技能。

    计算机服务规范.pdf

    计算机服务规范.pdf

    Discuz-X3.2-TC-UTF8.zip

    Discuz_X3.2_TC_UTF8.zip LNMP搭建安装包

    2023年房地产行业研究报告:缓解竣工下行加速的两大改革.pdf

    2023年房地产行业研究报告:缓解竣工下行加速的两大改革

    win32汇编环境,网络编程入门之十五

    win32汇编环境,网络编程入门之十五

Global site tag (gtag.js) - Google Analytics