Dojo data store-Unified Data access interface

Source: Internet
Author: User
Document directory
  • Read
  • Write
  • Notification
  • Identify

 

This article has been first published on the infoq Chinese site and is copyrighted. The original Article is "dojo data store-Unified Data access interface". If you need to reprint it, please attach this statement. Thank you.
Infoq Chinese site is an online independent community for mid-and high-end technical personnel ,. net, Ruby, SOA, agility, architecture and other fields to provide timely and in-depth information, high-end technology conferences such as qcon, offline technology exchange activities qclub, free mini book download such as architect, etc..

 

Data remains at the core of traditional desktop applications and mainstream Internet applications. At present, Web is a word that makes people familiar with, and the resulting data openness and sharing leads us into the era of massive data. Today, on the internet, data interaction has almost become our ultimate appeal. Data diversity, distributed storage and loose coupling of information can follow, along with the development of Ajax, Ria, and service-oriented network applications, the complexity of the client's data processing logic is increasing, making development more difficult. To simplify the data processing logic and increase the maintenance and scalability of applications, currently popular JavaScript frameworks also have their own data processing modules or interfaces. This article aims to introduce the data processing module of dojo: dojo. Data. As the middle layer of dojo data processing, its main responsibility is to parse and manage various types of data imported from the data source, and use the unified data access and processing interface and data display layer (Dojo widget) to facilitate management of various widgets and program transplantation.

Data Management in Dojo data

As Service-oriented applications are widely used today, the diversity of data coordination is an inevitable primary issue in the development of Internet applications. Our common data formats include JSON, XML, and CSV. As the middle layer of data processing, it is a basic requirement to allow users to connect to different data sources with a unified interface. In dojo. in the data module, different datastores are predefined for accessing and managing data sources of different data formats, and all datastores implement the same data access interface, in this way, the loose coupling between the data provision layer and the data presentation layer can be successfully realized. Table 1 lists various datastores that have been implemented in Dojo.

Table 1. Some datastore implemented in Dojo

Datastore Description
Dojo. Data. itemfilereadstore Read-Only datastore for JSON data
Dojo. Data. itemfilewritestore A readable datastore for JSON data
Dojox. Data. csvstore Read-Only datastore for CVS data
Dojox. Data. opmlstore Read-Only datastore for opml (outline processor Markup Language) data
Dojox. Data. htmltablestore Read-Only datastore for HTML table data
Dojox. Data. xmlstore A readable datastore for XML data
Dojox. Data. flickrstore Read-Only datastore used to read data provided by flickr.com. Is a good example of datastore related to Web Services.
Dojox. Data. queryreadstore Read-Only datastore for reading JSON data provided by the server

 

Despite the wide variety of data sources, in datastore, data organization and management are consistent through the Unified Data access interface. Each data item is used as an item object, which contains a certain attribute value pair to correspond to each attribute value in the data entry. The following uses a simple JSON data segment as an example to describe the corresponding relationship:

{    identifier: 'id',    label: 'name',    items: [        { "id": "AF", "name":"Africa", "type":"continent",          "population":"900 million", "area": "30,221,532 sq km" },        { "id": "AS", "name":"Asia", "type":"continent",          "population":"1 billion", "area": "25,428,192 sq km" }    ] }

There are two items in the JSON data, which contain five attribute fields: "ID", "name", "type", "population", and "area.

Dojo. Data Organizational Structure

To meet different requirements for the data middle layer in various applications, the dojo. Data Package classifies data access and processing interfaces to a certain extent, including read, write, identify, and notifaction. Various datastores can implement specific interfaces according to their application requirements.

Table 2. Main interfaces of dojo. Data. API

Main interfaces of dojo. Data Description
Dojo. Data. API. Read Provides the ability to read data items or their attribute values. It also supports searching, sorting, and filtering data sets.
Dojo. Data. API. Write This function allows you to create, delete, and update data items.
Dojo. Data. API. Identify Provides the ability to locate and query data items based on unique identifiers.
Dojo. Data. API. Notification Provides the function of notifying the listener when data items in datastore change or other events occur. The most basic events include data creation, modification, and deletion. This is also a very important function of dojo. data. This interface can be used to better separate the data presentation layer from the data middle layer.

 

Introduction to dojo. data API read

Data acquisition is the core of the Data middle layer. The dojo. Data. Read interface provides great convenience and flexibility for asynchronous access to heterogeneous data. In the read interface, data is obtained asynchronously, and basic functions such as data sorting, paging, and simple query are supported.

  • Fetch: function (/* object */keywordargs)
  • The fetch method is the core method of the dojo. data package. It uses an asynchronous method to obtain data. This method receives a key-Value Pair object parameter. You can specify the attributes of this parameter to obtain specific data sets, such as paging, simple query, filtering, and sorting. The following describes some main parameter attributes:

  • Onbegin and oncomplete: The fetch method is asynchronous for data acquisition. You can use the two parameters onbegin and oncomplete to specify the data acquisition callback function of the fetch method, onbegin is called once before the data is returned, and two parameters are passed in, respectively, the number of entries in the data set to be returned and the request object of the fetch. The oncomplete method is used as the callback function returned by the data, the dataset is passed into the callback function as the first parameter.
  • Start and count: Generally, almost all practical applications require that data be returned by page to provide a better user experience. The start and count attributes are implemented to support the paging function. Start is used to specify the start index of the returned data (starting from 0), while count is used to set the number of returned data entries.
  • Query: In addition to pagination, returning specific datasets on demand is also an important feature. In dojo. Data, this feature is supported by the query attribute. The query value can generally be set as a key-Value Pair object. The "key" should be set as an attribute in the data entry, while the "value" is specified as a condition. Dojo. Data provides exact match and fuzzy match (wildcard: * is any character ,? Is a single character) two ways to filter data, you can choose to use according to the specific situation.
  • Sort: Because Multiple widgets may use the same datastore, the dataset is not stored in a specific sequence. To sort data, you can specify it using the sort attribute, datastore returns a qualified dataset. The sort Parameter not only specifies the fields to be sorted, but also specifies the order in ascending or descending order.
    Datastore. fetch ({// set the start position of the retrieved data to start: 0, // set the number of retrieved data entries count: 25, // set the fuzzy filter condition query: {'name ': *}, // data sorting setting sort: [{attribute: 'name', descending: false}], // set the onbegin: function (size, requestobj ){...}, // set the callback function oncomplete after the data is obtained: function (items, requestobj ){...}, // set the onerror: function (error, requestobj) {...} callback function after data acquisition fails ){...}});
  • Getvalue: function (/* Item */item,/* Attribute-name-string */attribute,/* value? */Defaultvalue)

    Obtains the attribute value of a given data item. If this data item does not contain a specified attribute, a specified default value is returned. The item parameter is a given data item, the attribute parameter is the specified attribute field, and the defaultvalue is an optional parameter.

    var value = dataStore.getValue(item, 'name', 'no name'); 
  • Getattributes: function (/* Item */item)

    Obtains all attribute fields of a given data item. The returned value is an array.

Write

The dojo. Data. wirte interface provides APIs for data update, including creating, deleting, and updating data. Similar to the read interface, the write API is designed to avoid differences in underlying data storage formats and provide users with a unified data access API. With these APIs, you can focus on the logic implementation at the business layer without spending too much effort on the storage format of the underlying data.

  • Newitem: function (/* object? */Keywordargs,/* object? */Parentinfo)

    Create a new data item in datastore. The first parameter is a key-Value Pair object, which is used to set the newly created data item. The second parameter is an optional parameter, if you want to use the newly created data item as a child of an existing data item, you can set this parameter. For specific applications, see the following small example:

    VaR euitem = {"ID": "EU", "name": "Europe", "type": "Continent", "children ": []} // create a data item datastore. newitem (euitem); // create a sub-data item datastore. newitem ({"ID": "GM", "name": "Germany", "type": "country" },{ parent: euitem, attribute: "children "});
  • Deleteitem: function (/* Item */item)

    Delete a specified data item in datastore.

  • Setvalue: function (/* Item */item,/* string */attribute,/* almost anything */value)

    Updates the attribute value of a given data item.

Notification

When data is updated in datastore, the listener function defined in the corresponding notification is called. Readers who have used dojo will notice that there are generally no APIs common in Javascript library controls such as new and delete in widgets. This is because the design of dojo data is to split the data layer and the presentation layer, and to control data operations in the data layer, changes to the dataset can be automatically reflected in the application control. This function is implemented by the notification function of the notification interface when datastore performs data update operations.

  • Onnew: function (/* Item */newitem,/* object? */Parentinfo)

    This API is automatically called after a data item is created in datastore. The newitem parameter is the newly created data item object, and parentinfo is an optional parameter used to describe the parent data item of the newly created data item.

  • Ondelete: function (/* Item */deleteditem)

    It is automatically called when a data item is deleted in datastore. The deleteditem parameter is the deleted data item object.

  • Onset: function (/* Item */item,/* Attribute-name-string */attribute,/* object | array */oldvalue,/* object | array */newvalue)

    Call after a data item in datastore is updated. The four parameters are respectively the data item objects, the attributes of the updated data item, the original values of the data and the updated values.

Identify

Many data sources provide unique identifiers for data. The dojo. Data. Identify interface provides APIs for data retrieval and location based on unique identifiers.

  • Fetchitembyidentity: function (/* object */keywordargs)

    Similar to the fetch method in the read interface, this method is also an Asynchronous Method. You need to specify the callback processing function after the data item is obtained in the parameter object. The keywordargs parameter is a key-Value Pair object and mainly needs to include two attributes. One is the identify of the data item to be obtained, and the other is the onitem callback handler. After the specified identify data item is obtained successfully, the onitem callback function is automatically called to process subsequent operations.

    Datastore. fetchitembyidentity ({// ID identity of the data item to be retrieved: "as", // set the callback function onitem: function (item) {…} after the data is returned ){...}, // Set the error callback function onerror: function (error ){...}});
  • Getidentity: function (/* Item */item)

    This method is used to obtain the identifier of a given data item.

Datastore Application

In general, each part of dijit provides support for datastore. When we use a widget for data presentation, generally, you only need to select datastore based on the data source format type, and then specify datastore In the widget declaration. Next we will use the DataGrid and ComboBox as the data display UI, and set different datastore for them based on different data formats.

The following is a piece of JSON data:

data = {    identifier: 'id',     label: 'name',    items:  [        { "id": "AF", "name":"Africa", "type":"continent",          "population":"900 million", "area": "30,221,532 sq km" },        { "id": "AS", "name":"Asia", "type":"continent",          "population":"1 billion", "area": "25,428,192 sq km" },        { "id": "OC", "name":"Oceania", "type":"continent",          "population":"21 million", "area": "15,928,294 sq km" },        { "id": "EU", "name":"Europe", "type":"continent",          "population":"56 million", "area": "25,928,294 sq km" },        { "id": "NA", "name":"North America", "type":"continent",          "population":"100 million", "area": "90,928,294 sq km" },        { "id": "SA", "name":"South America", "type":"continent",          "population":"102 million", "area": "78,928,294 sq km" },        { "id": "AN", "name":"Antarctica", "type":"continent",          "population":"998", "area": "102,928,294 sq km" }]};

Here, we use the relatively simple dojo. Data. itemfilereadstore:

var jsonStore = new dojo.data.ItemFileReadStore({data: data}); 

Itemfilereadstore is suitable for processing data sources with a small amount of data. The data source can be a JSON file or a group of data directly specified to the client memory as in this example. When you use a larger JSON data set, you can use jsonreststore and use the rest service to provide data.

Next, we will declare a DataGrid. Here, datastore is set through the "Store" attribute.

<table jsid="grid" store="jsonStore" query="{name:’*'}" dojoType="dojox.grid.DataGrid" class="grid">    <thead>        <tr>            <th field="name" width="auto">Name</th>            <th field="population" width="auto">Population</th>            <th field="area" width="auto">Area</th>        </tr>    </thead></table>

Shows the generated DataGrid:

Because of the loose coupling between the data presentation layer and the Data Middle Layer in Dojo, the same data source can provide data for Multiple widgets without any processing, in addition, because data filtering, sorting, and paging are all returned on Demand Based on Data Acquisition requests, there will be no conflict between Multiple widgets using the same datastore. The following uses the same datastore to provide data for dijit. Form. ComboBox:

<input dojoType="dijit.form.ComboBox" store="jsonStore" searchAttr="name"></input> 

In many practical applications, different data sources may be used. Below, we use different data formats to replace itemfilereadstore with xmlstore. First, convert JSON data to XML data format:

<continents>    <continent>        <name>Africa</name>        <population>900 million</population>        <area>30,221,532 sq km</area>    </continent>    <continent>        <name>Asia</name>        <population>1 billion</population>        <area>25,428,192 sq km</area>    </continent>    <continent>        <name>Oceania</name>        <population>21 million</population>        <area>15,928,294 sq km</area>    </continent>    <continent>        <name>Europe</name>        <population>56 million</population>        <area>25,928,294 sq km</area>    </continent>    <continent>        <name>North America</name>        <population>100 million</population>        <area>90,928,294 sq km</area>    </continent>    <continent>        <name>South America</name>        <population>102 million</population>        <area>78,928,294 sq km</area>    </continent>    <continent>        <name>Antarctica</name>        <population>998</population>         <area>102,928,294 sq km</area>    </continent></continents>

Xmlstore is a client data storage used to read XML data sources. It is officially provided by dojo and included in the dojox sub-project. Xmlstore provides read/write interfaces for basic XML data (a common data exchange format. Xmlstore is useful for common XML documents. The storage design is that you can customize the reading/writing behavior by overwriting some of its methods. The following example shows how to create an xmlstore and apply it to grid and ComboBox:

var xmlStore = new dojox.data.XmlStore({    url: ‘continents.xml’,    label: ‘name’}); <table jsid="grid" store="xmlStore" dojoType="dojox.grid.DataGrid" class="grid">    <thead>        <tr>            <th field="name" width="auto">Name</th>            <th field="population" width="auto">Population</th>            <th field="area" width="auto">Area</th>        </tr>    </thead></table><input dojoType="dijit.form.ComboBox" store="xmlStore" searchAttr="name">

We almost don't need to modify any code about grid and ComboBox, so that they can continue to work. The only change that needs to be made is to declare a data source and set it as the grid input. We don't need to worry about data acquisition, parsing, and management. Data Storage APIs do all the work.

As you can see, as the data middle layer, dojo. data fully achieves the loose coupling between the data presentation layer and data management layer through excellent API design, at the same time, the unified data access interface makes it very convenient for applications with multiple data formats and program transplantation.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.