- 浏览: 9270 次
- 性别:
- 来自: 南京
最新评论
-
since1027:
Backbone系列教程的最后一章了,希望对Backbone入 ...
Part 8: Understanding Backbone.js Events
When we talk about any MV* pattern, model is undoubtedly the most important part of the architecture/application. Its the model that contains all the application data. Along with keeping the data the model class performs various set of actions on the data. Actions like possibility to validate the data, possibility to persist the data, defining access to various parts of data contained in the model (access control).
Backbone.js models are also the most important building blocks when it comes to building backbone.js applications. It keeps track of application data, perform validations on data and provide a mechanism to persist the data either locally on localstorage or remotely on a server using a web service.
Link to complete series:
Creating a simple backbone.js Model
To create a backbone model, we simply need to extend the backbone model class. Following code snippet shows how this can be done.
Furthermore, if we want to create a model that inherits from our model class then we just need to extend from our model class.
Instantiating a Model
Backbone models can simply be instantiated by using the new keyword.
Deleting a model
To delete a model, we just need to call the destroy function on the model.
Sometimes deleting a model could take some time(depending on the size of the model). In such cases we can define a function that will be called when the model get successfully deleted.
Cloning a model
Often times we would want to have a deep copied object or clone of a model. To create clone of a backbone model we simply need to call the clone method.
How to specify the model attributes
Backbone models does not enforce defining the attributes in the model definition itself i.e. one can create a model and specify the attributes on the fly. Lets say we want to create 2 attributes in our Book model. lets try to create them on the fly.
Default values of model attributes
Now creating the attributes on the fly is supported by the backbone models and it is a very powerful feature. But this feature actually becomes proves to be a maintenance nightmare when it comes to working with large scale application. From a maintainable application perspective and also from a best practices perspective, I would like the possibility to define my models attributes in my model definition itself.
To accomplish this, the default function can be used. The default function is used to specify the default attributes of the model and their default values. Lets try to move the attributes in the model definition now.
This way just instantiating the model will be enough and the created models will have these attributes associated with them.
Setting and getting model attributes
Once we specify the model attributes, we need to be able to get and set their values too. To do this we can use the get and set functions on the model.
How to check attribute existence
Since backbone allows us to add attributes on the fly, we need some way to identify whether a particular attribute exist in the model or not. To do this we can use the has function on model.
Defining Functions in a Model
We can also define our functions in the model classes. Lets try to create a simple function in our model class.
The initialize function
Whenever we create a model, the backbone will call its initialize function. We can override this function to provide custom behavior to it.
Listening Model attribute changes
We can also use the events to listen to the model changes. This can be done by listening to the change event. backbone raises a change event whenever any model attribute is changed. For each attribute we can use hasChanged method to check if that attribute has been changed or not. Lets try to hook up the event handler to listen to the model change in our current model.
[size=large]
If we have a lot of attributes and we are interested in listening to change for any specific attribute then perhaps we can specify that too in the change event binding. Lets try to listen to the BookName change only.
Point of Interest
So that is for this blog. the idea behind this article was to get familiar with the basic concepts of the backbone model. In next article of this series, we will look at more advanced topics associated with the backbone model. This article has been written from beginner’s perspective, I hope this has been informative.
原文链接:http://rahulrajatsingh.com/2014/07/backbone-tutorial-part-2-understanding-the-basics-of-backbone-models/
Backbone.js models are also the most important building blocks when it comes to building backbone.js applications. It keeps track of application data, perform validations on data and provide a mechanism to persist the data either locally on localstorage or remotely on a server using a 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
Creating a simple backbone.js Model
To create a backbone model, we simply need to extend the backbone model class. Following code snippet shows how this can be done.
var Book = Backbone.Model.extend({ });
Furthermore, if we want to create a model that inherits from our model class then we just need to extend from our model class.
var ChildrensBook = Book.extend({ });
Instantiating a Model
Backbone models can simply be instantiated by using the new keyword.
var book = new Book();
Deleting a model
To delete a model, we just need to call the destroy function on the model.
book.destroy();
Sometimes deleting a model could take some time(depending on the size of the model). In such cases we can define a function that will be called when the model get successfully deleted.
book.destroy({ success: function () { alert("The model has been destroyed successfully"); } });
Cloning a model
Often times we would want to have a deep copied object or clone of a model. To create clone of a backbone model we simply need to call the clone method.
function cloneModel() { var book = new Book(); var book2 = book.clone(); }
How to specify the model attributes
Backbone models does not enforce defining the attributes in the model definition itself i.e. one can create a model and specify the attributes on the fly. Lets say we want to create 2 attributes in our Book model. lets try to create them on the fly.
var book = new Book({ ID: 1, BookName: "Sample book" });
Default values of model attributes
Now creating the attributes on the fly is supported by the backbone models and it is a very powerful feature. But this feature actually becomes proves to be a maintenance nightmare when it comes to working with large scale application. From a maintainable application perspective and also from a best practices perspective, I would like the possibility to define my models attributes in my model definition itself.
To accomplish this, the default function can be used. The default function is used to specify the default attributes of the model and their default values. Lets try to move the attributes in the model definition now.
var Book = Backbone.Model.extend({ defaults: { ID: "", BookName: "" }, });
This way just instantiating the model will be enough and the created models will have these attributes associated with them.
Setting and getting model attributes
Once we specify the model attributes, we need to be able to get and set their values too. To do this we can use the get and set functions on the model.
var book = new Book(); book.set("ID", 3); book.set("BookName", "C# in a nutshell"); var bookId = book.get('ID'); var bookName = book.get('BookName');
How to check attribute existence
Since backbone allows us to add attributes on the fly, we need some way to identify whether a particular attribute exist in the model or not. To do this we can use the has function on model.
book.has('ID'); // true book.has('author'); // false
Defining Functions in a Model
We can also define our functions in the model classes. Lets try to create a simple function in our model class.
var Book = Backbone.Model.extend({ defaults: { ID: "", BookName: "" }, showAlert: function () { alert('ID: ' + this.get('ID') + ', BookName: ' + this.get('BookName')); } });
The initialize function
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'); }, showAlert: function () { alert('ID: ' + this.get('ID') + ', BookName: ' + this.get('BookName')); } });
Listening Model attribute changes
We can also use the events to listen to the model changes. This can be done by listening to the change event. backbone raises a change event whenever any model attribute is changed. For each attribute we can use hasChanged method to check if that attribute has been changed or not. Lets try to hook up the event handler to listen to the model change in our current model.
[size=large]
var Book = Backbone.Model.extend({ defaults: { ID: "", BookName: "" }, initialize: function(){ console.log('Book has been intialized'); // Lets hook up some event handers to listen to model change this.on('change', function() { if(this.hasChanged('ID')){ console.log('ID has been changed'); } if(this.hasChanged('BookName')){ console.log('BookName has been changed'); } }); }, showAlert: function () { alert('ID: ' + this.get('ID') + ', BookName: ' + this.get('BookName')); } });[/size]
If we have a lot of attributes and we are interested in listening to change for any specific attribute then perhaps we can specify that too in the change event binding. Lets try to listen to the BookName change only.
var Book = Backbone.Model.extend({ defaults: { ID: "", BookName: "" }, initialize: function () { console.log('Book has been intialized'); // Lets hook up some event handers to listen to model change this.on('change:BookName', function () { console.log('Message from specific listener: BookName has been changed'); }); }, showAlert: function () { alert('ID: ' + this.get('ID') + ', BookName: ' + this.get('BookName')); } });
Point of Interest
So that is for this blog. the idea behind this article was to get familiar with the basic concepts of the backbone model. In next article of this series, we will look at more advanced topics associated with the backbone model. This article has been written from beginner’s perspective, I hope this has been informative.
原文链接:http://rahulrajatsingh.com/2014/07/backbone-tutorial-part-2-understanding-the-basics-of-backbone-models/
- backboneModelsSampleApp.zip (127.3 KB)
- 下载次数: 0
发表评论
-
Part 8: Understanding Backbone.js Events
2016-06-22 10:34 827In this article, we will look a ... -
Part 7: Understanding Backbone.js Routes and History
2016-06-22 09:52 558In this article, we will try to ... -
Part 6: Understanding Backbone.js Views
2016-06-22 09:50 723In this article, we will try to ... -
Part 5: Understanding Backbone.js Collections
2016-06-21 14:39 641In this article we will discuss ... -
Part 4: CRUD Operations on BackboneJs Models using HTTP REST Service
2016-06-21 14:21 904In this article we will discuss ... -
Part 3: More about Backbone Models
2016-06-21 14:08 760In this article we will look at ... -
Part 1: Introduction to Backbone.Js
2016-06-21 11:12 724It was a long time ago (almost ...
相关推荐
《 Beginning jQuery:From the Basics of jQuery to Writing your Own Plug-ins》是Jack Franklin和Russ Ferguson合著的一本关于jQuery的入门教程。这本书旨在帮助读者从零基础开始,逐步掌握jQuery的核心概念,并...
Part 2: Custom Types – Project2: Fixed-point Numbers Part 3: Generic Programming – Function Templates Part 3: Generic Programming – Class Templates Part 3: Generic Programming – Template ...
An easy introduction to Computational Fluid Dynamics.... Covers the basics - grid generation, numerics, incompressible flow and supersonic flow. Motivates the reader with many examples.
Introducing ZFS on Linux Understand the Basics of Storage with ZFS 英文无水印原版pdf pdf所有页面使用FoxitReader、PDF-XChangeViewer、SumatraPDF和Firefox测试都可以打开 本资源转载自网络,如有侵权,请...
The author has explored every component of Hadoop. Prior to that, the author helps you understand how to setup Hadoop on your Linux platform. The Hadoop HDFS has been explored in detail. You will ...
It is an SDK sample produced by members of the ATL (Active Template Library) team chartered with building an ATL-based wrapper around the windowing portions of the Win32 API. Since version 2.0, ATL ...
The Basics of Cloud Computing
4CHAPTER 2:Understanding Access-Control and Monitoring Systems +CHAPTER 3:Understanding Video Surveillance Systems +CHAPTER 4:Understanding Intrusion-Detection and Reporting Systems +CHAPTER 5:...
PART 2: CORE CONCEPTS 3 Pods: running containers in Kubernetes 4 Replication & other controllers: deploying managed pods 5 Services: enabling clients to discover and talk to pods 6 Volumes: attaching ...
In addition, it helps individuals who have worked in stale- or siloed-thinking enterprises make the transition to a process or improvement-oriented culture and teaches those who are unfamiliar with ...
PART II: LEARNING THE NOSQL BASICS CHAPTER 4: UNDERSTANDING THE STORAGE ARCHITECTURE 73 CHAPTER 5: PERFORMING CRUD OPERATIONS 97 CHAPTER 6: QUERYING NOSQL STORES 117 CHAPTER 7: MODIFYING DATA ...
integrated with computer-aided design software, facilitates the production of P&IDs;. There are several process simulation software systems available to the chemical engineering community, and Aspen ...
2: From Basics to Practice By 作者: Andrew Glassner Pub Date: 2018 ISBN: n/a Pages: (914 of 1750) Format: PDF Publication Date: February 19, 2018 Language: English ASIN: B079Y1M81K People are using ...
### 基础理解财务报表的关键知识点 #### 一、财务报表概述 本书《基础理解财务报表》旨在帮助初级投资者了解如何阅读财务报告。对于初次涉足投资领域的人来说,掌握基本的会计知识至关重要,因为这是商业语言的...
Deep learning is fast becoming part of the intellectual toolkit used by scientists, artists, executives, doctors, musicians, and anyone else who wants to discover the information hiding in their data,...
2. **黑客攻击手段**:书中列举了一些常见的黑客攻击手段,如: - **社会工程学**:通过欺骗或心理操纵来获取敏感信息。 - **缓冲区溢出**:利用程序内存管理中的缺陷执行恶意代码。 - **SQL注入**:向数据库查询...