I am creating a social website based on jquery mobile. Pages are loaded dynamically using AJAX and are cached in DOM (jQM manages this). I have a chat system on the site: when user click on a name on the contact list page (/chat/), a page with the conversation history with the selected contact loads (/char/msg/?u=user_name).
The problem: when user is chatting with multiple (n) users at the same page, n instances of the conversation page will be loaded and stored on the DOM (/chat/msg/?u=user_1, /chat/msg/?u=user_2, …, /chat/msg/?u=user_n). IDs of elements on the conversation page will inevitably conflict which will break the chatting functionality.
How should I manage the conversation pages to avoid ID conflicts? Destroying all other conversation pages when switching to one is not an option — I would like to support fast-switching between the conversations. I noticed that GMail and Facebook assign random unique ID in such cases but that’s the best practices of doing this? Is there a pattern that I can make use of? And is there a simpler solution?
Thank you.
This is a common issue when getting used to jQuery Mobile. The solution is that if you find yourself using the same ID on multiple pseudo-pages, then stop, and make them classes instead. It’s as easy as changing the
idattribute toclassfor any element that uses an ID in a non-unique way.Here is an example:
You can then use
$.mobile.activePage.find('.back-btn')to find the back button for the current page, or you could use$('#some-page').find('.back-btn')to target a specific back button.Basically my suggestion boils down to using page ids as the unique part of your selectors and then using classes for anything more specific so each page can have the same structure. This will help you write re-usable code as well.