Dojo1.6 new feature: dojo object stores

Source: Internet
Author: User
Tags wrappers

This article translated from: dojo object
Stores

Original Author: Kris zyp

Translation: Siqi

 

Dojo 1.6 introduces a new data store API named dojo object store. This set is based on HTML5 indexeddb object
Store API

The new store API aims to greatly simplify the interaction and construction of the dojo store.

 

This new API complies with the HTTP/rest naming rules and works with dojox. Storage
Providers

(Local Storage, Cookie storage, and websql
Storage) and all other libraries that comply with these open standards.

 

The following are the core concepts of the new store API:

  • User interface and data separation

    -This has long been our data API design goal.
    These APIs help us to separate user interfaces from data so that we can independently improve widgets or data providers.

  • Simplicity first

    -
    You can simply create an object instance with query () and get () methods. The returned values of these methods are objects. This object instance is an available store. When you want to add other functions, such as creating a new object, you can add an add () method. Similarly, you can introduce a put () method to update the object function.

  • Simple JavaScript Object

    -This new object store
    APIs use simple JavaScript objects instead of opaque items (opaque
    Items ). When you use the get () method to return an object or query () to return an object array, you can use the for-in loop to access the attributes of these objects. To save an object, you only need to pass a simple object to the put () method.

  • Based on promise

    -
    The synchronous method and the Asynchronous Method interface are basically the same. The only difference is that the synchronous method directly returns the value while the Asynchronous Method returns the promise. You can select synchronous mode or asynchronous mode (return promise) for any method ). Since callback functions are no longer required, the interaction with the known synchronization store is greatly simplified. At the same time, the troubles brought by asynchronous mode are separated from interfaces, greatly simplifying the API.

  • Clear Functions

    -
    No additional method is required to determine a store function. If you want to know whether you can add a new object to a store, you only need to check whether it has the add () method. If you want to know whether the store is queryable, you only need to check whether the query () method exists. If you want to create a read-only store, you only need to implement some read functions (get, query, getidentity ).

  • Hierarchical Functions

    -
    Hierarchical functions enable you to gradually add required functions from a simple and lightweight store. The dojo core library is equipped with a cache package (caching
    Wrapper) (Dojo/store/cache) to improve performance and a data change notification package (Dojo/store/observable ). The hierarchical modules of these stores are optional and can be added to any store. This allows us to keep our core store-Dojo/store/memory and dojo/store/jsonrest simple and lightweight, and allows users to easily create new stores.

Dojo object store
An API is an interface between different data providers and data consumers. You can use this interface to implement any store, while the dojo core library is configured with two common core stores: dojo/store/memory and dojo/store/jsonrest.

 

Simple: dojo/store/memory

This is a very simple in-memory store. It is very useful for quickly creating a store,
Especially for small datasets. Simply provide an array as the data source, you can create a memory
Then you can start querying and interacting with the store. (For more details, see memory object store.
Documentation

)

 

Memory store is a synchronization mode store, that is, it directly returns a value, which makes it very simple to use. For example, get an object by ID:

 

VaR Product = productstore. Get ("slinky ");

 

It should be emphasized that the new object store returns a simple object, so we can easily obtain the attributes:

 

VaR name = product. Name;

 

Using simple objects makes it very easy to update the store:

 

Product. Name = "new name"; <br/> productstore. Put (product );

 

The improved query function is Dojo object.
One of the new functions of stores. Query is implemented by using the query () method, and the returned result set provides a series of convenient Iteration Methods (interative
Methods) -- very similar to dojo. query -- sotre in both synchronous and asynchronous modes provides this function. Therefore, you can use foreach, map, or filter to operate the result set. Memory
Store supports multiple forms of queries. First, we can use the key-value match (name-Value
Matches) to query (the same as itemfilereadstore in Dojo. Data ). We can query the data by category as follows:

 

Store. Query ({category: "shoe"}). foreach (function (shoe) {<br/> // called upon successful match <br/> });
 

 

Key-value matching provides a simple query mechanism, but sometimes requires more complex queries. Memory
Store also accepts functions for filtering, so any complicated query is allowed. For example, to query all products with prices less than 10:

 

Store. query (function (product) {<br/> return product. price <10; <br/> }). foreach (function (shoe) {<br/> // called when each matching succeeds <br/> });

 

 

We can also reference a function by using a function name. In essence, it refers to a method with the same name in store.

 

Store. lessthanten = function (product) {<br/> return product. price <10; <br/>}); <br/> store. query ("lessthanten "). foreach (function (shoe) {<br/> // called when each matching succeeds <br/> });

 

JSON and rest: dojo/store/jsonrest

Jsonrest
Assume that a server-side API exists, and the API is intended to interact with the store. It implements a robust and standard HTTP/rest client interface. Dojo/store/jsonrest follows the High-scalability principle of rest and is very suitable for large datasets. Jsonrest is a store in asynchronous mode, and all its asynchronous Methods return promise (the getidentity method is always synchronous ).

 

JSON rest object
The interaction between store and HTTP-compatible servers is similar to that between dojox. Data. jsonreststore. However, jsonrest is in the store
The API reconstruction process has been greatly simplified. You can create a jsonrest store by simply providing a URL to the server. (For more information, see jsonrest object store.
Documentation

):

 

Store = new dojo. Store. jsonrest ({target: "/data /"});

The store method is very intuitive and corresponds to the HTTP method. Store. Get ("Some-ID") will send a GET request to/data/Some-ID and return a promise/deferred as the result. For example:

 

Store. Get ("Some-ID"). Then (function (someobject) {<br/> // use someobject <br/> });

 

Store. Remove (ID) sends a Delete request accordingly. Add (object) and put (object) will also trigger the corresponding request. If the object passed to put (object) (or add (object) has the identity attribute, A put request is sent. If the object does not contain an ID or the second parameter (options) contains an incremental attribute with the value true, a POST request is sent.

 

If options. Overwrite is true, the request containsIf-Match: *

Header. If options. Overwrite is false or add (object) is usedIf-None-Match:
*

Header. Such communication between servers usually occurs when an object is created or changed.

 

Synchronous and asynchronous Standardization

 

If you are writing a store with synchronous and asynchronous operations, we recommend using dojo. When (). Because the then () method is valid only when the store method is asynchronous, it is not worth full dependency in this case. We can use dojo. when (), any returned value will be properly processed.

 

Dojo. when (store. get (ID), function (object) {<br/> // this function will be called when the get () method is complete, whether a promise or <br/> // directly return a value <br/> });

 

The dojo. When () method can be applied to all store methods.

 

Client data cache: dojo/store/Cache

In addition to the core store implementation, dojo is also equipped with two store wrappers (wrappers ). The first one is Dojo/store/cache. This package needs to be used with two stores: A Caching
And a master store. A typical cache package uses jsonrest as the master store and uses memory
As the caching store of the client. This allows you to use jsonrest store to communicate with the server and use memory
Store to cache to avoid unnecessary HTTP requests. Here is an example to illustrate how to build it:

 

Memorystore = new dojo. store. memory ({}); <br/> reststore = new dojo. store. jsonrest ({target: "/data/"}); <br/> store = new dojo. store. cache (reststore, memorystore );

 

Now we can use the Integrated store to execute a query. Next we will query all the objects (we can omit the query conditions to query the objects ):

 

VaR Results = store. Query ();

 

This causes the returned results to be cached in the memory store. Then we can get an object through the get () method without sending an additional HTTP request:

 

Object = store. Get ("Some-ID ");

 

Changes made to the data through the put (), add (), and remove () methods are reflected in the cached data. Queries usually require fine-grained applications to control which data needs to be cached and which do not. Therefore, Cache
Store does not attempt to automatically query the cache. However, if you choose to use the cache for queries, there is no problem. You can simply query caching
Store, that is, memorystore in our example:

 

Memorystore. Query ({category: "shoe"}). foreach (...);

Monitoring data changes: dojo/store/observable

Dojo also comes with a store package to add support for data change notifications. Dojo object store API and legacy dojo data
API notification mechanisms are very different. There is a problem with the old API. Notifications are stored at the store level. Therefore, it is impossible to determine how an event actually affects a rendered dataset.

 

Dojo object
Store solves this problem by binding monitoring of notification events to the query result set instead of store. Through the dojo/store/observable module, you can wrap a store, and the query result set obtained by the packaged store is "monitorable )". That is to say, the objects/arrays/promise returned by the query () method have an observe () method that can be used to monitor changes in the result set. See observable store wrapper
Documentation for the exact signature of the observe () method and
Callback

.

 

Observable
The module makes it easy to render a result set and update the interface in real time based on changes in the underlying data. Let's look at an example. We will create an unordered list (<ul>) based on the stored object ). First, create a list, and then we will give feedback based on data changes:

 

// Add the monitoring function to our store first <br/> store = dojo. store. observable (store); <br/> var listnode = dojo. byid ("list"); <br/> var itemnodes = []; <br/> // query data now <br/> var shoes = store. query ({category: "shoe"}); <br/> // then render the returned data <br/> Shoes. foreach (function (shoe) {<br/> // render each node <br/> insertrow (shoe, itemnodes. length); <br/>}); <br/> // Changes in our monitoring result set <br/> Shoes. observe (function (object, removedfrom, insertedinto) {<br/> If (removedfrom>-1) {// Deleted Data <br/> dojo. destroy (itemnodes [removedfrom]); <br/> itemnodes. splice (removedfrom, 1); <br/>}< br/> If (insertedinto>-1) {// new data or updated data <br/> insertrow (object, insertedinto); <br/>}< br/> }); <br/> function insertrow (product, index) {<br/> return itemnodes. splice (index, 0, dojo. create ("Li", <br/> {innerhtml: product. name + ":" + product. price}, listnode); <br/>}< br/>

 

By setting up a monitoring function that can delete and Add rows, we can basically cope with any data changes, including adding, deleting, and updating. The observable module even monitors the update of indexes, so that if the sorting order of the result set changes, the updated objects can be correctly moved to the point pointed by a new index. Note that, in this example, by listening to the shoes result set, we will only obtain updates related to the matching result set. If an object is updated, deleted, or added, and its category attribute is not "shoe", no notification time will be sent to the listener. If an object is not
"Shoe" is updated to "shoe", which triggers a notification to add data to the result set. If an object is "shoe" and is not "shoe" after update, a notification is triggered to delete data from the dataset.

 

The observable module also adds an notify () method to store. This is very useful for Comet-driven real-time applications because they will asynchronously receive updates from the server and inform the store (and the listeners in all store result sets ). More
For details about comet and real-time applications in section 1.6, see dojo
Socket

.

 

Work with existing widgets and store

Most dijit widgets are still based on the legacy dojo data API. However, Dojo configures an adapter to allow users
Use the new object store on the Data widget. Dojo/data/ObjectStore

The module accepts an object as the configurator.
Store and return a Data Store. Dojo also configures an adapter that allows the use of the widgets of object store to be compatible with the legacy data store. Dojo/store/datastore

The module accepts a data store and returns an object store.

 

Hierarchical Structure

The object store API defines a method used to implement a hierarchical structure-getchildren (object, options ). Getchildren
It is generally called by a parent object and returns its child element set. The implementation of getchildren is generally customized according to application requirements, but there are also many common implementation methods:

  • Contains"
    Array of child elements

    -In this way, each object defines its child elements in an array, so the sequence of child elements is reserved. This method is suitable for small datasets.

  • Reference containing a parent Element

    -In this way, each object defines its parent element and obtains all its child elements by querying all objects under the parent element with a given ID. This method is suitable for large datasets that may require additional processing such as paging or sorting.

Compatible with other stores

Because store API is a common mode, many library interfaces can be easily compatible with store API. Dojox. storage providers
The API is similar to the store API, except for the put () method. This method can be easily converted:

 

VaR storage = dojo. delegate (dojox. storage); <br/> var storage. put = function (object, options) {<br/> var deferred = dojo. deferred (); <br/> dojox. storage. put (options. id | object. ID, object, function (Status) {<br/> If (status = dojox. storage. failed) {<br/> deferred. reject (Status); <br/>} else if (status = dojox. storage. success) {<br/> deferred. resolve (Status); <br/>}< br/>}); <br/> return deferred; <br/> };

 

Or we can set Jens Arps storagejs
Library

For conversion, the original use of the Set () method instead of the put () method:

 

VaR store = dojo. delegate (storage); <br/> var store. put = function (object, options) {<br/> return storage. set (options. id | object. ID, object); <br/> };

 

The storagejs API also has an allkeys () method that can be converted to the query () method.

Object stores

In order to absorb the essence of dojo. Data and comply with the HTML5 indexeddb standard, while simplifying the use and hierarchical functionality, the new dojo object
The store architecture has been thoroughly reconstructed. It is exciting that we can finally use this new method to build our applications. We also look forward to the valuable comments of the dojo community on this design.

 

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.