use*_*897 262 javascript jquery html5 jquery-mobile cordova
我正在使用jQuery Mobile,我无法理解经典文档就绪和jQuery Mobile页面事件之间的差异.
真正的区别是什么?
为何要
<!-- language: lang-js -->
$(document).ready() {
});
Run Code Online (Sandbox Code Playgroud)
比...更好
$(document).on('pageinit') {
});
Run Code Online (Sandbox Code Playgroud)当您从一个页面转换到另一个页面时,页面事件的顺序是什么?
如何将数据从一个页面发送到另一个页面,是否可以从上一页访问数据?
Gaj*_*res 438
My original article was intended for old way of page handling, basically everything before jQuery Mobile 1.4. Old way of handling is now deprecated and it will stay active until (including) jQuery Mobile 1.5, so you can still use everything mentioned below, at least until next year and jQuery Mobile 1.6.
Old events, including pageinit don't exist any more, they are replaced with pagecontainer widget. Pageinit is erased completely and you can use pagecreate instead, that event stayed the same and its not going to be changed.
如果您对新的页面事件处理方式感兴趣,请查看此处,在任何其他情况下,请随时继续阅读本文.即使您使用的是jQuery Mobile 1.4 +,也应该阅读此答案,它超越了页面事件,因此您可能会发现许多有用的信息.
这篇文章也可以在我的博客HERE中找到.
$(document).on('pageinit') VS $(document).ready()The first thing you learn in jQuery is to call code inside the $(document).ready() function so everything will execute as soon as the DOM is loaded. However, in jQuery Mobile, Ajax is used to load the contents of each page into the DOM as you navigate. Because of this $(document).ready() will trigger before your first page is loaded and every code intended for page manipulation will be executed after a page refresh. This can be a very subtle bug. On some systems it may appear that it works fine, but on others it may cause erratic, difficult to repeat weirdness to occur.
Classic jQuery syntax:
$(document).ready(function() {
});
Run Code Online (Sandbox Code Playgroud)
为了解决这个问题(并且相信我这是一个问题),jQuery Mobile开发人员创建了页面事件.简而言之,事件是在特定页面执行中触发的事件.其中一个页面事件是一个pageinit事件,我们可以像这样使用它:
$(document).on('pageinit', function() {
});
Run Code Online (Sandbox Code Playgroud)
我们可以更进一步,使用页面ID而不是文档选择器.假设我们有一个带有id 索引的 jQuery Mobile页面:
<div data-role="page" id="index">
<div data-theme="a" data-role="header">
<h3>
First Page
</h3>
<a href="#second" class="ui-btn-right">Next</a>
</div>
<div data-role="content">
<a href="#" data-role="button" id="test-button">Test button</a>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
要执行仅对索引页可用的代码,我们可以使用以下语法:
$('#index').on('pageinit', function() {
});
Run Code Online (Sandbox Code Playgroud)
Pageinit event will be executed every time page is about be be loaded and shown for the first time. It will not trigger again unless page is manually refreshed or Ajax page loading is turned off. In case you want code to execute every time you visit a page it is better to use pagebeforeshow event.
Here's a working example: http://jsfiddle.net/Gajotres/Q3Usv/ to demonstrate this problem.
Few more notes on this question. No matter if you are using 1 html multiple pages or multiple HTML files paradigm it is advised to separate all of your custom JavaScript page handling into a single separate JavaScript file. This will note make your code any better but you will have much better code overview, especially while creating a jQuery Mobile application.
还有另一个特殊的jQuery Mobile事件,它被称为mobileinit.当jQuery Mobile启动时,它会触发文档对象上的mobileinit事件.要覆盖默认设置,请将它们绑定到mobileinit.mobileinit使用的一个很好的例子是关闭Ajax页面加载或更改默认的Ajax加载器行为.
$(document).on("mobileinit", function(){
//apply overrides here
});
Run Code Online (Sandbox Code Playgroud)
首先可以在这里找到所有活动:http://api.jquerymobile.com/category/events/
假设我们有一个页面A和一个页面B,这是一个卸载/加载顺序:
第B页 - 事件pagebeforecreate
第B页 - 事件页面创建
第B页 - 事件pageinit
第A页 - 事件pagebeforehide
第A页 - 事件页面删除
第A页 - 事件页面隐藏
第B页 - 事件pagebeforeshow
第B页 - 活动页面显示
为了更好的页面事件理解阅读:
pagebeforeload,pageload并pageloadfailed在加载外部页面时触发pagebeforechange,pagechange并pagechangefailed在页面更改事件.当用户在应用程序中的页面之间导航时会触发这些事件.pagebeforeshow,pagebeforehide,pageshow和pagehide是页面转换事件.这些事件在转换之前,期间和之后被触发并被命名.pagebeforecreate,pagecreate并且pageinit是页面初始化.pageremove 可以触发,然后在从DOM中删除页面时进行处理Page loading jsFiddle example: http://jsfiddle.net/Gajotres/QGnft/
If AJAX is not enabled, some events may not fire.
If for some reason page transition needs to be prevented on some condition it can be done with this code:
$(document).on('pagebeforechange', function(e, data){
var to = data.toPage,
from = data.options.fromPage;
if (typeof to === 'string') {
var u = $.mobile.path.parseUrl(to);
to = u.hash || '#' + u.pathname.substring(1);
if (from) from = '#' + from.attr('id');
if (from === '#index' && to === '#second') {
alert('Can not transition from #index to #second!');
e.preventDefault();
e.stopPropagation();
// remove active status on a button, if transition was triggered with a button
$.mobile.activePage.find('.ui-btn-active').removeClass('ui-btn-active ui-focus ui-btn');;
}
}
});
Run Code Online (Sandbox Code Playgroud)
This example will work in any case because it will trigger at a begging of every page transition and what is most important it will prevent page change before page transition can occur.
Here's a working example:
jQuery Mobile works in a different way than classic web applications. Depending on how you managed to bind your events each time you visit some page it will bind events over and over. This is not an error, it is simply how jQuery Mobile handles its pages. For example, take a look at this code snippet:
$(document).on('pagebeforeshow','#index' ,function(e,data){
$(document).on('click', '#test-button',function(e) {
alert('Button click');
});
});
Run Code Online (Sandbox Code Playgroud)
Working jsFiddle example: http://jsfiddle.net/Gajotres/CCfL4/
Each time you visit page #index click event will is going to be bound to button #test-button. Test it by moving from page 1 to page 2 and back several times. There are few ways to prevent this problem:
Best solution would be to use pageinit to bind events. If you take a look at an official documentation you will find out that pageinit will trigger ONLY once, just like document ready, so there's no way events will be bound again. This is best solution because you don't have processing overhead like when removing events with off method.
Working jsFiddle example: http://jsfiddle.net/Gajotres/AAFH8/
This working solution is made on a basis of a previous problematic example.
Remove event before you bind it:
$(document).on('pagebeforeshow', '#index', function(){
$(document).off('click', '#test-button').on('click', '#test-button',function(e) {
alert('Button click');
});
});
Run Code Online (Sandbox Code Playgroud)
Working jsFiddle example: http://jsfiddle.net/Gajotres/K8YmG/
Use a jQuery Filter selector, like this:
$('#carousel div:Event(!click)').each(function(){
//If click is not bind to #carousel div do something
});
Run Code Online (Sandbox Code Playgroud)
Because event filter is not a part of official jQuery framework it can be found here: http://www.codenothing.com/archives/2009/event-filter/
In a nutshell, if speed is your main concern then Solution 2 is much better than Solution 1.
A new one, probably an easiest of them all.
$(document).on('pagebeforeshow', '#index', function(){
$(document).on('click', '#test-button',function(e) {
if(e.handled !== true) // This will prevent event triggering more than once
{
alert('Clicked');
e.handled = true;
}
});
});
Run Code Online (Sandbox Code Playgroud)
Working jsFiddle example: http://jsfiddle.net/Gajotres/Yerv9/
Tnx to the sholsinger for this solution: http://sholsinger.com/archive/2011/08/prevent-jquery-live-handlers-from-firing-multiple-times/
pageChange event quirks - triggering twice
Sometimes pagechange event can trigger twice and it does not have anything to do with the problem mentioned before.
The reason the pagebeforechange event occurs twice is due to the recursive call in changePage when toPage is not a jQuery enhanced DOM object. This recursion is dangerous, as the developer is allowed to change the toPage within the event. If the developer consistently sets toPage to a string, within the pagebeforechange event handler, regardless of whether or not it was an object an infinite recursive loop will result. The pageload event passes the new page as the page property of the data object (This should be added to the documentation, it's not listed currently). The pageload event could therefore be used to access the loaded page.
In few words this is happening because you are sending additional parameters through pageChange.
Example:
<a data-role="button" data-icon="arrow-r" data-iconpos="right" href="#care-plan-view?id=9e273f31-2672-47fd-9baa-6c35f093a800&name=Sat"><h3>Sat</h3></a>
Run Code Online (Sandbox Code Playgroud)
To fix this problem use any page event listed in Page events transition order.
As mentioned, when you change from one jQuery Mobile page to another, typically either through clicking on a link to another jQuery Mobile page that already exists in the DOM, or by manually calling $.mobile.changePage, several events and subsequent actions occur. At a high level the following actions occur:
This is a average page transition benchmark:
Page load and processing: 3 ms
Page enhance: 45 ms
Transition: 604 ms
Total time: 670 ms
*These values are in milliseconds.
So as you can see a transition event is eating almost 90% of execution time.
It is possible to send a parameter/s from one page to another during page transition. It can be done in few ways.
Reference: /sf/answers/975256831/
Solution 1:
You can pass values with changePage:
$.mobile.changePage('page2.html', { dataUrl : "page2.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : true, changeHash : true });
Run Code Online (Sandbox Code Playgroud)
And read them like this:
$(document).on('pagebeforeshow', "#index", function (event, data) {
var parameters = $(this).data("url").split("?")[1];;
parameter = parameters.replace("parameter=","");
alert(parameter);
});
Run Code Online (Sandbox Code Playgroud)
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<title>
</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js">
</script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script>
$(document).on('pagebeforeshow', "#index",function () {
$(document).on('click', "#changePage",function () {
$.mobile.changePage('second.html', { dataUrl : "second.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : false, changeHash : true });
});
});
$(document).on('pagebeforeshow', "#second",function () {
var parameters = $(this).data("url").split("?")[1];;
parameter = parameters.replace("parameter=","");
alert(parameter);
});
</script>
</head>
<body>
<!-- Home -->
<div data-role="page" id="index">
<div data-role="header">
<h3>
First Page
</h3>
</div>
<div data-role="content">
<a data-role="button" id="changePage">Test</a>
</div> <!--content-->
</div><!--page-->
</body>
</html>Run Code Online (Sandbox Code Playgroud)
second.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<title>
</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js">
</script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
</head>
<body>
<!-- Home -->
<div data-role="page" id="second">
<div data-role="header">
<h3>
Second Page
</h3>
</div>
<div data-role="content">
</div> <!--content-->
</div><!--page-->
</body>
</html>Run Code Online (Sandbox Code Playgroud)
Solution 2:
Or you can create a persistent JavaScript object for a storage purpose. As long Ajax is used for page loading (and page is not reloaded in any way) that object will stay active.
var storeObject = {
firstname : '',
lastname : ''
}
Run Code Online (Sandbox Code Playgroud)
Example: http://jsfiddle.net/Gajotres/9KKbx/
Solution 3:
You can also access data from the previous page like this:
$(document).on('pagebeforeshow', '#index',function (e, data) {
alert(data.prevPage.attr('id'));
});
Run Code Online (Sandbox Code Playgroud)
prevPage object holds a complete previous page.
Solution 4:
As a last solution we have a nifty HTML implementation of localStorage. It only works with HTML5 browsers (including Android and iOS browsers) but all stored data is persistent through page refresh.
if(typeof(Storage)!=="undefined") {
localStorage.firstname="Dragan";
localStorage.lastname="Gaic";
}
Run Code Online (Sandbox Code Playgroud)
Example: http://jsfiddle.net/Gajotres/J9NTr/
Probably best solution but it will fail in some versions of iOS 5.X. It is a well know error.
.live()/.bind()/.delegate()I forgot to mention (and tnx andleer for reminding me) use on/off for event binding/unbinding, live/die and bind/unbind are deprecated.
The .live() method of jQuery was seen as a godsend when it was introduced to the API in version 1.3. In a typical jQuery app there can be a lot of DOM manipulation and it can become very tedious to hook and unhook as elements come and go. The .live() method made it possible to hook an event for the life of the app based on its selector. Great right? Wrong, the .live() method is extremely slow. The .live() method actually hooks its events to the document object, which means that the event must bubble up from the element that generated the event until it reaches the document. This can be amazingly time consuming.
It is now deprecated. The folks on the jQuery team no longer recommend its use and neither do I. Even though it can be tedious to hook and unhook events, your code will be much faster without the .live() method than with it.
Instead of .live() you should use .on(). .on() is about 2-3x faster than .live(). Take a look at this event binding benchmark: http://jsperf.com/jquery-live-vs-delegate-vs-on/34, everything will be clear from there.
There's an excellent script made for jQuery Mobile page events benchmarking. It can be found here: https://github.com/jquery/jquery-mobile/blob/master/tools/page-change-time.js. But before you do anything with it I advise you to remove its alert notification system (each "change page" is going to show you this data by halting the app) and change it to console.log function.
Basically this script will log all your page events and if you read this article carefully (page events descriptions) you will know how much time jQm spent of page enhancements, page transitions ....
Always, and I mean always read official jQuery Mobile documentation. It will usually provide you with needed information, and unlike some other documentation this one is rather good, with enough explanations and code examples.
Mat*_*ius 17
有些人可能会觉得这很有用.只需将其粘贴到您的页面即可,您将获得一个在Chrome控制台(Ctrl+ Shift+ I)中触发事件的序列.
$(document).on('pagebeforecreate',function(){console.log('pagebeforecreate');});
$(document).on('pagecreate',function(){console.log('pagecreate');});
$(document).on('pageinit',function(){console.log('pageinit');});
$(document).on('pagebeforehide',function(){console.log('pagebeforehide');});
$(document).on('pagebeforeshow',function(){console.log('pagebeforeshow');});
$(document).on('pageremove',function(){console.log('pageremove');});
$(document).on('pageshow',function(){console.log('pageshow');});
$(document).on('pagehide',function(){console.log('pagehide');});
$(window).load(function () {console.log("window loaded");});
$(window).unload(function () {console.log("window unloaded");});
$(function () {console.log('document ready');});
Run Code Online (Sandbox Code Playgroud)
您不会在控制台中看到卸载,因为在卸载页面时(当您离开页面时)会触发它.像这样使用它:
$(window).unload(function () { debugger; console.log("window unloaded");});
Run Code Online (Sandbox Code Playgroud)
你会明白我的意思.
| 归档时间: |
|
| 查看次数: |
151368 次 |
| 最近记录: |