开发者

What is the best method for running JavaScript per page in jQuery Mobile?

I'm really struggling to get my head round jQuery Mobile. I understand the DOM is inserted with the contents of each new page using AJAX for caching purposes. However, normally my development consists of usin开发者_C百科g JavaScript in the jQuery ready event.

As a simple example, I have a page which shows an address, and a google map of the location. The pointer on the map is set via JavaScript.

When the map is shown, the address shows correctly (pulled in from MVC controller), but then I want the snippet of JavaScript to run to put the postcode on the map.

Now this is pretty simple stuff, but it seems I have to jump through hoops to get this to work. I've seen examples of binding to pageshow/pagecreate events, but I want my script to run only on the map page. The pageshow/create events end up firing on every page, not what I want!!

So this really comes down to:

  1. Running a snippet of JavaScript on a SPECIFIC page being shown.
  2. Dynamically calling some JavaScript with the postcode from the model.

How can I do this? I've even thought about trying Sencha touch to say how it goes about managing this.


It is best to use different pages and not to embed all pages in one document. Also you can use rel="external" on each page within your site so that Ajax is NOT used. This way you can embed jQuery elements as needed instead of loading it all at once.


I think I have the answer I was after. Although the rel="external" AFAIK forces a non-AJAX load of the page and therefore runs any script in the head section, this is missed in subsequent requests. After the first AJAX request made by jQM, the contents of the page are pulled in from its internal cache, without running any script. I think the jQM site has added a page that describes this behaviour:

http://jquerymobile.com/demos/1.0b2/#/demos/1.0b2/docs/pages/page-scripting.html

As Phill mentioned above, the live event can be used in the JavaScript of the main startup page. Just ensure the div with the data-role="page" id matches with what you are binding the 'pagecreate' event to:

$('#aboutPage').live('pagecreate',function(event){
  alert('This page was just enhanced by jQuery Mobile!');
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜