In-depth analysis of data sharing and data transfer in JavaScript _ javascript skills

Source: Internet
Author: User
This article focuses on the in-depth analysis of data sharing and data transmission in JavaScript. For more information, see data sharing and data transmission. The first thing we should talk about is that sharing and transmission are all in scope. The scope is the region in which the data in the same scope can be shared. If the scope is exceeded, the data is transferred across scopes.

Scope

1. ui Scope

By default, each ui file has a corresponding ui. js. They act as a closed scope. Ui. js obtains the ui object based on the component id in the ui file. Different ui files can define components with the same id. Variables defined in ui. js can only be accessed in this js.

2. page Scope

Each time you call openPage, a new page is opened. The new page is built on the old page. When closePage is closed, the old page is exposed. In addition to the main ui file, each page can contain many other ui files in the same page scope.
When the page is closed, all objects built in the page will be released.

3. app Scope

This is the largest scope. As long as the app does not exit, this scope will always be valid.

App. js belongs to the app scope because it does not belong to any page.

In short, the app scope contains multiple page scopes, and the page scope contains multiple ui scopes.

Memory Sharing

Compared with files and databases, the memory operation speed is much faster and is suitable for operations with a small amount of data. The disadvantage is that the app is released after it is closed. Deviceone shares the memory in the following ways.

1. do_Global memory Operation (app scope)

This is app-scope data sharing. This memory is actually a key-value pair, and a key corresponds to a value. Therefore, if you assign a value to a key again, the previous value will be overwritten. It is easy to use. Refer to the following example to read and write data on different pages.

// Set the value in index. ui. js to any json object, except for function objects. Global. setMemory ("key1", 1); global. setMemory ("key2", "value1"); global. setMemory ("key3", ["a", "B", "c"]); global. setMemory ("key4", {"k1": "v1", "k2": "v2", "k3": "v3", "k4 ": "v4"}); var label = ui ("do_Label_2"); // in memory/index. ui. get the value in js and return the json object var global = sm ("do_Global"); var content ={}; content. key1 = global. getMemory ("key1"); content. key2 = global. getMemory ("key2"); content. key3_2 = global. getMemory ("key3") [1]; content. key4_k3 = global. getMemory ("key4") ["k3"]; label. text = JSON. stringify (content, null, 2); // format

2. Global variables of Javascript (page scope)

Using the features of JavaScript to define global variables, you can usually define global variables to share data in different ui files on the same page. For the following example, read and write are in different ui files, but in a page scope. It is also very simple to use, there are two ways:

Although it is very convenient, it is not recommended because it is too casual. If it is a collaborative development or complex project, it is difficult to locate and debug bugs.

// Set js global variables in test1.ui. js in two ways. // 1. do not add a variable definition with the var prefix, key1 = "value1"; // 2. define global variables on the deviceone object. key2 = {"k1": "v1", "k2": "v2", "k3": "v3", "k4": "v4"} // In test2.ui. obtain test1.ui in js. the global variables defined in js are two methods. Var content ={}; content. key1 = key1; content. key2_k3 = deviceone. key2 ["k3"];

3. Javascript variables (ui scope)

This does not need to be explained too much. It is the normal js variable definition, which can only be valid in the current ui. js scope.

var key1 = "value1"; 

4. sqlite memory mode

Sqlite is usually a file mode. In special cases, sqlite can be used directly in the memory. This mode is suitable for complicated data structures and troublesome text operations. It is much more flexible to use SQL statements.

There can be only one memory mode with a fixed name: memory \:.

We will introduce the sqlite database in detail later.

File Sharing

We understand that file sharing applies to the app and can be accessed after the app is restarted. You can use the do_Storage component to write content to a file anywhere in the app, and then read the content from another file. Refer to the following example to read and write data on different pages. Note that file reading and writing is usually asynchronous. You must ensure that the content has been written before reading.

// In index. ui. write files file1 and file2 in js. You can directly write the json object var key1 = "value1"; storage. writeFile ("data: // file1", key1, function (data, e) {// After the callback, the content is actually written, if the file may not be read before execution,}) var key2 = {"k1": "v1", "k2": "v2", "k3 ": "v3", "k4": "v4"}; storage. writeFile ("data: // file2", key2, function (data, e) {// After the callback, the content is actually written, if you have read the file before the execution, you may not be able to read the data}) // In datacache/index. ui. the json object var datacache = sm ("do_DataCache"); var content ={}; content. key1 = datacache. loadData ("key1"); content. key2_3 = datacache. loadData ("key2") ["k3"]; label. text = "datacache/index. ui. to get the value in js, you can directly return the json object \ n "+ JSON. stringify (content, null, 2); // format

Do_SQLite component Accessing Database Data

This component is a MM component, which means you can create multiple instances. By default, all MM components are page-specific or app-specific. Create the third parameter of the MM component to indicate the scope.

Note that SQLite reads and writes are usually asynchronous. You must ensure that the content has been written before reading

1. app scope:

// Create an app-specific sqlite object. The second parameter indicates the object. The third parameter indicates the appvar sqlite_app = mm ("do_SQLite", "sqlite_app_id1 ", "app") function test_sqlite () {// in index. ui. js uses this object to create a database test. dbsqlite_app.open ("data: // test. db "); var stu_table =" drop table if exists stu_table "// synchronously execute a SQL statement sqlite_app.exe cuteSync (stu_table ); // create table SQL statement stu_table = "create table stu_table (_ id integer primary key autoincrement, sname text, snumber Text) "; // synchronously execute a SQL sentence sqlite_app.exe cuteSync (stu_table); var stu_ SQL =" insert into stu_table (sname, snumber) values ('xiaoming', '123 '); "+" insert into stu_table (sname, snumber) values ('xiaohong ', '000000'); "+" insert into stu_table (sname, snumber) values ('xiaoliu ', '20140901') "; // execute a SQL statement sqlite_app.exe cute (stu_ SQL, function (data, e) {// This callback completes the data insertion, if data is queried before execution, deviceone may not be read. print ("insert fin Ished! ")}) // Obtain an sqlite object in the app scope based on the id" sqlite_app_id1 ". The second parameter is the identifier of this object, the third parameter indicates the scope of appvar sqlite_app = mm ("do_SQLite", "sqlite_app_id1", "app") // In sqlite/index. ui. use this object in js to query test. db, because this object has already opened the database, you do not need to open it again // create a query SQL statement var stu_query = "select * from stu_table "; // synchronously execute a query statement var result = sqlite_app.querySync (stu_query); label. text = "in sqlite/index. ui. use this object in js to query test. the second data entry of the stu_table table in the db "+ JSON. stringify (result [1], null, 2 );

2. page scope:

// Create a page-scoped sqlite object. The unique id is memory_db_id1var sqlite_app = mm ("do_SQLite", "memory_db_id1", "page"); // In test1.ui. js uses this object to create a memory database. This name must be written to: memory: sqlite_app.open (": memory :"); // create a table SQL statement var stu_table = "drop table if exists stu_table;" // The execution speed of the memory database is fast. You can try to execute a sqlite_app.exe cuteSync (stu_table) simultaneously ); stu_table = "create table stu_table (_ id integer primary key autoincrement, sname text, snumber text)"; // synchronously execute a SQL sentence sqlite_app.exe cuteSync (stu_table); var stu_ SQL = "insert into stu_table (sname, snumber) values ('lasting', '1'); "+" insert into stu_table (sname, snumber) values ('laohong ', '2 '); "+" insert into stu_table (sname, snumber) values ('laoliu', '3') "; // execute sqlite_app.exe cuteSync (stu_ SQL) synchronously; // In test2.ui. query in test1.ui. database Table created in js // obtain the created sqlite object var sqlite_app = mm ("do_SQLite", "memory_db_id1", "page") based on the memory_db_id1 mark "); // create a query SQL statement var stu_query = "select * from stu_table"; // execute a query statement var result = sqlite_app.querySync (stu_query) synchronously; label. text = "in test2.ui. query in test1.ui. the third record of the memory database table created in js \ n "+ JSON. stringify (result [2], null, 2)

Data Transmission

Data transmission involves transferring data across scopes, such as different ui files and different pages.

The most important and common method is the message mechanism.

1. Message Mechanism

This step is detailed in the document.

In short, the message mechanism can transmit data across the ui scope or across the page scope.

2. Use openPage and closePage to transmit data.

This data transfer is across page scopes, but only between two pages. For example, if page2 is enabled on the basis of page1, page1 Transmits some data to page2; page2 closes itself to expose page1, and data can be transmitted back to page1. data can be any json object.
This is a common and very good method. We recommend that you use this method.

// In index. ui. open_close_page/index. ui, pass data var d = {"k1": "v1", "k2": "v2", "k3": "v3", "k4 ": "v4"}; app. openPage ({source: "source: // view/open_close_page/index. ui ", data: d, statusBarState:" transparent "}) ;}// accept open_close_page/index on the page. the data page passed back when the ui is disabled. on ("result", function (data) {if (data) nf. alert (JSON. stringify (data, null, 2);}) // from index. ui. the data transmitted by js gets the value through getData, And the json object var data = page can be directly returned. getData (); label. text = "from index. ui. the data passed by js gets the value through getData, And the json object \ n "+ JSON can be directly returned. stringify (data, null, 2); // format function close_me () {// close itself and pass the data back to the next pageapp. closePage ("I'm from open_close_page/index. the data passed when the ui is disabled ");}

The js data sharing and data transmission related knowledge introduced in this article is so much for you and I hope it will be helpful to you!

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.