MUI Window management

Source: Internet
Author: User

1. Page initialization

In app development, to use the html5+ extension API, you must wait for the Plusready event to work, and the MUI encapsulates the event as a Mui.plusready () method, involving the html5+ API. The recommendations are written in the Mui.plusready method. The following is an example of printing the current page URL:

Mui.plusready (function () {    console.log ("current page URL:" +plus.webview.currentwebview (). GetURL ());}); Mui.init ()    MUI plug-in initializes Mui.ready ()    when the DOM is ready, specify a function to execute.

code block activation character: Minit


2. Create a sub-page

In mobile app development process, often encounter card end of the page, at this time if using local scrolling, on the Android phone will appear the problem of scrolling is not smooth, MUI's solution is: the need to scroll the area through a separate WebView implementation, full use of native scrolling. This is done by decomposing the target page into the main page and the content page, the main page showing the end of the card, such as the top navigation, the bottom tab, etc., the content page displays the content that needs scrolling, and then invokes the Mui.init method to initialize the content page in the main page.

Mui.init ({    subpages:[{      url:your-subpage-url,//child page HTML address, support for local address and network address      id:your-subpage-id,//child page flag      styles:{        top:subpage-top-position,//Sub-page top position        bottom:subpage-bottom-position,//sub-page at the bottom of the position        width: subpage-width,//Child page width, default is 100%        height:subpage-height,//child page height, default is 100%        ...      },      extras:{}// Additional extended Parameters    }]  });

Parameter Description: Styles represents the window properties, refer to the Webviewstyle in the 5+ specification; note that the height and width two properties, even if not set, are calculated by default by 100%, so if the top value is not "0px", It is recommended to set the bottom value at the same time, otherwise the 5+ runtime is calculated based on height 100%, which may cause the actual bottom position of the page to exceed the screen range; left and right.

Example: The first page of Hello MUI is actually a combination of index.html plus list.html, as follows:


 index.htmlis to display fixed navigation,list.htmlDisplays specific list contents, and the scrolling of list items islist.htmlwhereWebViewusing native scrolling ensures that the scroll bar does not penetrate the top navigation,appexperience, but also ensures a smooth scrolling of the list, solving the problem of regional rolling lag. list.htmlis thatindex.htmlSub-page, creating code is simple, as follows:

Mui.init ({    subpages:[{      url: ' list.html ',      ID: ' list.html ',      styles:{        top: ' 45px ',// The MUI title bar default height is 45px;        bottom: ' 0px '//default is 0px, not defined;      }    ]  });


code block activation character: Misubpage


3. Open a new page

As a web app, a problem that can't be avoided is the transition animation; The web is built based on links, from one page click links to another page, if you have a refreshing open way, users have to face a blank page to wait; Using JavaScript to move into DOM nodes (a common spa solution) has high performance challenges: DOM nodes are numerous, pages are too large, transitions are not smooth, and even browsers crash; the solution to the MUI is that the single WebView only hosts the DOM of a single page, Reduce DOM levels and page size; page switching uses native animations to give the most-consumed parts to the native implementation.

Mui.openwindow ({    url:new-page-url,    Id:new-page-id,    styles:{      top:newpage-top-position,//The top position of the new page      bottom:newage-bottom-position,//new Page bottom position      width:newpage-width,//new page width, default is 100%      height:newpage-height ,//New page height, defaults to 100% ...    },    extras:{...      //Custom extension parameters, which can be used to process the value of the page between pages    },    createnew:false,/ /whether to repeat the creation of WebView with the same ID, default to False: Do not repeat creation, direct display    show:{      autoshow:true,//Page loaded event occurs automatically, default is True      anishow:animationtype,//page display animation, default to "Slide-in-right",      duration:animationtime//page animation duration, Android platform default 100 milliseconds, iOS platform default 200 milliseconds;    },    waiting:{      autoshow:true,//automatically display the Wait box, default to True      title: ' Loading ... ',//Wait for the dialog box to display the prompt content      options:{        width:waiting-dialog-widht,//The width of the background area of the Wait box, by default automatically calculates the appropriate width based on the content        height:waiting-dialog-height,/ /wait box background area height, by default automatically calculates the appropriate height according to the content ...}}    )


Parameters:

(1), Styles

Window parameters, refer to the Webviewstyle in the 5+ specification; note that the height and width two properties, even if not set, are calculated by default by 100%, so if the top value is not "0px", it is recommended to set the bottom value at the same time, otherwise 5+ Runtime is calculated based on height 100%, which may cause the actual bottom position of the page to exceed the screen range;

(2), extras

Additional extension parameters for the new window, which can be used to handle the transfer of values between pages, for example:

var WebView = Mui.openwindow ({url: ' info.html ', Extras:{name: ' MUI '  //Extended parameter}}); Console.log (webview.name);// Output MUI string

Note: The extension parameter is only valid when a new window is opened, and if the target window is a preloaded page, the extras parameter passed when opened by the Mui.openwindow method is invalid.

(3), CreateNew

Whether to repeat the creation of WebView with the same ID, to optimize performance, to avoid repeated creation of Webview,mui v1.7.0 in the app, to start adding createnew parameters, the default is false;

A, the createnew parameter is true, then does not judge duplicates, each time creates the new WebView;

b, the createnew parameter is Fasle, first find whether the current app already has the same ID webview, if present, directly display, otherwise create and execute the display logic according to the show parameters;

Note: The Plusready event is triggered only when WebView is first created, and when you use the Mui.openwindow method to open the webview of an existing same ID multiple times, the Plusready event is not repeated, so if the business is written in a Plusready event , the results of execution and expected inconsistencies may occur, and can be triggered by custom events.

(4), show

window Display control parameters, the specific parameters are as follows:

A, AutoShow: if the target window loaded event occurs, is automatically displayed, the default is true, if False, only the WebView is created but not displayed, if the target page is preloaded page, the parameter is invalid;

B, anishow means that the page display animation, such as from the right side, from the bottom of the row, and so on, specifically can refer to the 5+ specification Animationtypeshow

C, Duration: Displays the duration of the WebView window animation, in MS

(5), waiting

The system waits for the box parameter. When the MUI framework opens a new page, the Wait box's processing logic is: Show Wait box--Create target page webview--> target page loaded event occurs--close wait box, so only when new page is newly created page (WebView), the Wait box is displayed , otherwise if the page is preloaded, the target page is displayed directly and no wait box is displayed. Specific parameters in the waiting:

A, AutoShow: whether to automatically display the Wait box, the default is true, if false, the wait box is not displayed, note: If the waiting box AutoShow is true, but the target page does not automatically display, You need to close the wait box in the target page by using the following code: Plus.nativeUI.closeWaiting ();

B. Title: Prompt text on the wait box

c, options indicate waiting box display parameters, such as width, background color, hint text color, etc., can refer to the 5+ specification Waitingoption

Example 1: Hello MUI , click the icon in the top right corner of the homepage to open the About page, the implementation code is as follows:

Tap for MUI-encapsulated Click events, refer to the Gesture Events section document.getElementById (' Info '). AddEventListener (' tap ', function () {  //open About page  Mui.openwindow ({    URL: ' examples/info.html ',    ID: ' Info '  });

Because the styles parameter is not passed in, it is displayed by default, and the show parameter is not passed, so the new page slides in from the right side using the Slide-in-right animation.

Example 2: from a page open b page, b page is a list page that needs to be loaded from the server, if b page loaded

The first step, b page Loaded event occurs, does not automatically display;

A page opens the B page, setting show's AutoShow to False, then the B page is not automatically displayed after its loaded event, Mui.openwindow ({    URL: ' b.html ',    show:{      Autoshow:false    }  });

Second, after the B page to get the list data, and then close the wait box, display b page

b page onload gets list data from the server; window.onload = function () {  //Get data from server  ....  The business data is finished and inserted into the current page DOM;  //NOTE: If you are an AJAX request, you need to place the following code after processing the AJAX response data;  Mui.plusready (function () {    //close Wait box    plus.nativeUI.closeWaiting ();    Show current page    mui.currentWebview.show ();  });}

code block activation character: Mopenwindow

4. Close the page

The MUI framework encapsulates the window closure function in the Mui.back method, with the following logic: If the current webview is a preloaded page, hide is currently webview; otherwise, close is currently webview;

In the MUI framework, there are three actions that trigger a page close (the Mui.back method is executed):

A, click the control that contains the. Mui-action-back class

b, in the screen, the right to quickly swipe

C, Android phone press the back button

iOS platform native support right slide off from the edge of the screen. iOS platform can be implemented by Popgesture parameters from the edge of the screen to the right slide off WebView, refer to the 5+ specification, if you want to disable this feature, you can set Popgesture to None by SetStyle method.

Hbuilder Mheader generated code block will automatically generate a title bar with a return navigation arrow, click the back arrow to close the current page, because the return arrow contains the. Mui-action-back class, the code is as follows:

If you want to add a control that closes the page in a different area than the top navigation bar, simply add the. Mui-action-back class to the corresponding control, as shown below as an example of a close button:

<button type= "button" class= ' mui-btn mui-btn-danger mui-action-back ' > Close </button>

The MUI framework encapsulates the right-slide-off feature of the page, which is not enabled by default, to use the right-slide-off feature, you need to set the Swipeback parameter in the Mui.init () method, as follows:

Mui.init ({swipeback:true//enable right slide off function});

The MUI framework listens to the back button of the Android phone by default, then performs the page shutdown logic, and if you do not want the MUI to automatically process the back button, turn off the MUI's Back button monitoring as follows;

Mui.init ({keyeventbind: {backbutton:false  //Close Back button listener}});

In addition to the above three operations, you can call the Mui.back () method directly, execute the window close logic, Mui.back () only handle the window logic, if you want to process some other business logic before the window closes, you can abstract the business logic into a specific function, The Beforeback parameter of the Mui.init method is then registered, and the execution logic of Beforeback is: if the function corresponding to the Beforeback parameter returns FALSE, the Mui.back () method is no longer executed, otherwise (returns TRUE or no return value). Continue to implement the Mui.back () method;

Example: To open the details page from the list, and then return from the Details page to refresh the list interface, you can register the Beforeback parameter and then refresh the data through the Custom Event notification list page with the sample code as follows:

Mui.init ({beforeback:function () {///Get list interface Webviewvar list = plus.webview.getWebviewById (' list ');// Trigger the custom event (refresh) of the list interface for data refresh Mui.fire (list, ' Refresh ');//returns TRUE to continue the page close logic return true;});

Note: Beforeback execution return must be synchronous (blocking mode), if using Nativeui asynchronous JS (non-blocking mode), you may have unexpected results, such as: Through the plus.nativeUI.confirm () Pop-up confirmation box, Perhaps the user has not selected, the page has been returned (Beforeback synchronous execution, no return value, continue to execute the Mui.back () method, Nativeui will not block the JS process): In this case, to customize the business logic, You need to make a copy of the Mui.back method; The following is a custom example that will not close the current page until the user is confirmed

Backup Mui.back,mui.back has closed the Windows logical encapsulation (preload and parent-child window), so it is best to reuse mui.backvar Old_back = Mui.back;mui.back = function () {  var BTN = ["OK", "Cancel"];  Mui.confirm (' Confirm closing the current window? ', ' Hello mui ', Btn,function (e) {    if (e.index==0) {    ////Execute MUI packaged window close logic;    old_back ();    }  });}

Why is Swipeback:false set up and can still be turned right on iOS? iOS platform native support from the screen edge right slide off, this is controlled by the Popgesture parameter, refer to the 5+ specification, if you want to disable, you can set Popgesture to None by SetStyle method.

Can you implement custom shutdown logic by AddEventListener adding back key monitoring? AddEventListener will only add new execution logic, and old listening logic (Mui.back) will still execute, so if you need to implement custom shutdown logic, you must rewrite Mui.back.

code block activation character: Mback

5. Pre-loading

The so-called preload technology is to create the target page in advance when the user has not triggered the page jump, so that when the user jumps, you can immediately switch the page, save time to create a new page, improve the app experience. MUI provides two ways to implement page preloading.

(1), mode one: Through the Mui.init method in the preloadpages parameter configuration.

Mui.init ({  preloadpages:[    {      url:prelaod-page-url,      id:preload-page-id,      styles:{},//window parameters      extras:{},//Custom Extension parameters      subpages:[{},{}]//pre-load page    }  ],  preloadlimit:5//number of pre-loaded windows (once exceeded, FIFO only) No Limit By default});

This scheme is simple to use, can preload multiple pages, but does not return a reference to preload each page, to obtain a corresponding WebView reference, It also needs to be obtained by means of plus.webview.getWebviewById, and because Mui.init is executed asynchronously, a corresponding WebView reference is obtained immediately after execution of the Mui.init method, such as the following code:

Mui.init ({  preloadpages:[    {      URL: ' list.html ',      ID: ' List '    }  ]}); var list = Plus.webview.getWebviewByid (' list ');//may return empty here;

(2), mode two: pre-loading by Mui.preload method.

var page = mui.preload ({    url:new-page-url,    id:new-page-id,//default uses the URL of the current page as the ID    styles:{},//window parameter    extras:{}//custom extension parameters});

by preloading the Mui.preload () method, a reference to the corresponding WebView can be returned immediately, but only one page can be preloaded at a time, and the Mui.preload () method needs to be called multiple times if multiple webview are to be loaded;

such as the above two options, each with advantages and disadvantages, according to the specific business scenarios flexible choice;

(3), determine whether the preload is successful

Method One, through the intuitive phenomenon analysis

The Pre-loaded page opens immediately without a wait box, and the non-preloaded page defaults to a wait box before displaying a new page;

Method Two, add log to analyze whether the pre-loaded page has been created

For example: A page pre-loading B page, then the a page fully loaded (can be simulated by settimeout), print the current application of all WebView, see if the URL of the B page, to analyze.

For example, add the following code to the a page:

Mui.plusready (function () {setTimeout (function () {var array = Plus.webview.all (); if (array) {for (Var i=0,len= array.length;i<len;i++) {    console.log (Array[i].geturl ());        }}},5000)});

code block activation Character: Minitpreload mpreload (Single webview)

MUI Window management

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.