jQuery Mobile + backbone.js: navbar issue - jquery-mobile

I load pages created from templates dynamically with a function from the Router (as seen on some tutorials):
changePage: function(page) { // page is a View object
$(page.el).attr('data-role', 'page');
page.render();
$('body').append($(page.el));
var transition = $.mobile.defaultPageTransition;
if (this.firstPage) {
transition = 'none';
this.firstPage = false;
}
$.mobile.changePage($(page.el), {changeHash:false, transition: transition});
}
The thing is when pages contain a JQ Mobile navbar, the active item is not highlighted. Actually it is, like 1 ms, then it's not, I feel like it's because the navbar is "reloaded".
When I click 2 times on the same item, it works the second time.
Is there anybody who is able to have working navbars with jQuery Mobile and backbone.js?

I ended up doing that:
var activeTab = null;
$('[data-role=page]').live('pageshow', function (event, ui) {
$.each($('[data-role=navbar] ul li').children(), function (i, val) {
if (typeof activeTab !== "undefined" && activeTab != null && $(val).attr('id') == 'navTab' + activeTab)
$(val).addClass($.mobile.activeBtnClass);
else
$(val).removeClass($.mobile.activeBtnClass);
});
activeTab = null;
});
And for each route that requires an active tab I just do for instance:
r_search: function() { // Search page (form)
activeTab = "Search";
this.changePage(new SearchView());
},

Related

How to get the newly loaded page on pageinit?

On page 1, when ajax loading to page 2, I need to get the [data-role=page] element of page 2,
but on pageinit(or pagecreate), the $.mobile.activePage is still page 1.
How to get the newly loaded page instead of the current page on pageinit?
$(document).on('pageinit', function () {
console.log($.mobile.activePage); // page 1
});
If you want to retrieve it one time only, then use pagecreate because it fires once per page and it fires before navigation is commenced.
$(document).on("pagecreate", function (e) {
if ( $(e.target).hasClass("ui-dialog") ) {
var dialog = $(e.target);
}
});
To retrieve it every time you navigate to it, you can use othe pageContainer events. In case you want to alter the page you're nacigating to, use pagecobtainerbeforechange.
$(document).on("pagecintainerbeforechange", function (e, data) {
if ( typeof data.toPage == "object" && typeof data.prevPage != "undefined" && data.toPage.hasClass("ui-dialog") ) {
data.toPage.find(".foo").addClass(".bar");
}
});
For other events in case you just want to access dialog and manipulate its markup.
$(document).on("pagecontainerbeforeshow pagecontainershow", function (e, data) {
if ( data.toPage.hasClass("ui-dialog") ) {
var dialog = data.toPage;
/* do something */
});

Swiping between html pages for Android app dev

I know this has been asked before but I can't get any of he examples to work.
Getting the slide transition to work where you have all the pages as separate html files seems very difficult to do? How does the next/prev part of the script know which of the other files is next?
For example, index.html should slide to 01_welcome.html - but how does it know that it's not 02_funds.html?
Thanks for any enlightenment you can give. Below is the script ( courtesy of a previous answer) I've been trying to implement.
$('div.ui-page').live("swipeleft", function () {
var nextpage = $(this).next('div[data-role="page"]');
if (nextpage.length > 0) {
$.mobile.changePage(nextpage, "slide", false, true);
}
});
$('div.ui-page').live("swiperight", function () {
var prevpage = $(this).prev('div[data-role="page"]');
if (prevpage.length > 0) {
$.mobile.changePage(prevpage, {
transition: "slide",
reverse: true
}, true, true);
}
});
The code in your OP works well in Multi-Page Model environment, since all pages (div's) are present in DOM. For Single Page Model, you will need to tweak the code a bit as each page is an individual file. Another note, .live() is deprecated, use .on() instead.
The simplest solution is to add custom attributes to each page div, e.g.
<div data-role="page" data-next-page="services" data-prev-page="about">
Retrieve the values of the custom attributes on swipe and then load the target page.
$(document).on("swipeleft swiperight", function (event) {
var activePage = $.mobile.pageContainer.pagecontainer("getActivePage"),
nextPage = activePage.data("next-page"),
prevPage = activePage.data("prev-page");
/* move to next page */
if (event.type == "swipeleft" && nextPage) {
$.mobile.pageContainer.pagecontainer("change", nextPage + ".html");
}
/* move to previous page */
if (event.type == "swiperight" && prevPage) {
$.mobile.pageContainer.pagecontainer("change", prevPage + ".html", {
reverse: true
});
}
});

Which page was just shown?

In 1.4.2, I have this:
$(document).on('pagecontainershow', PageShown);
function PageShown(myEvent, myUI ) {
log(this)
log(myEvent)
log(myUI)
};
I can't determine which page was just shown.
If I add more specificity to the selector, the event doesn't fire.
Update
As of jQuery Mobile 1.4.2 you can access previous .prevPage and next page .toPage.
$(document).on("pagecontainerhide", function (e, ui) {
var activePage = ui.toPage,
previousPage = ui.prevPage;
});
Both are jQuery objects so $() isn't needed.
To determine which page is currently active, you have two options:
Listen to pagecontainerhide and check ui.nextPage object emitted by that event
$(document).on("pagecontainerhide", function (e, ui) {
var activePage = $(ui.nextPage);
});
On pagecontainershow, use the below function which will return active page.
var activePage = $.mobile.pageContainer.pagecontainer("getActivePage");
Read more about page events.

Combining knockout with sammyjs/pathjs and jquery mobile

I'm trying to combine some of JS libraries to create a mobile SPA website. I'm working with knockoutJS that misses routing engine so I take it from SammyJS or PathJS (haven't decided yet). And I'd like to use jQuery Mobile to get the controls and the mobile design from it.
The thing is that whenever I include the jquery mobile js file into my page the routing engine stops working. Actually it does work, but the window.location.hash get changed not only by me but with jquery mobile itself.
So here is how the code looks like:
in the html file I got a div that I binded to a template
(function ($) {
infuser.defaults.templateUrl = "templates";
console.log('just before pageinit');
$(document).bind('pagecreate', function () {
// disable autoInit so we can navigate to bookmarked hash url
$.mobile.autoInitializePage = false;
// let PathJS handle navigation
$.mobile.ajaxEnabled = false;
$.mobile.hashListeningEnabled = false;
$.mobile.pushStateEnabled = false;
});
$(document).bind('pagebeforechange', function (e, data) {
var to = data.toPage;
if (typeof to === 'string') {
/* var u = $.mobile.path.parseUrl(to);
to = u.hash || '#' + u.pathname;
// manually set hash so PathJS will be triggered
location.hash = to;
// prevent JQM from handling navigation*/
e.preventDefault();
}
});
$(document).bind('pagechange', function (e, data) {
});
var Model = function () {
this.items = ko.observable(null);
this.chosenItemData = ko.observable();
this.state = ko.observable('items');
this.goToItemDetails = function (item) {
location.hash = '/details/' + item.id;
};
};
window.currentModel = new Model();
ko.applyBindings(window.currentModel);
Path.map('#home').to(function () {
currentModel.state(window.templates.items);
currentModel.items(window.dummyData);
});
Path.map('#home/details/:id').to(function () {
var self = this;
$(currentModel.items()).each(function (index, item) {
if (item.id.toString() == self.params['id']) {
currentModel.chosenItemData(item);
currentModel.state(window.templates.itemDetail);
}
});
});
Path.root('#home');
$(function () {
Path.listen();
})
})(jQuery);
Now, you can see that $.mobile.hashListeningEnabled = false; is set to false so the jquery mobile should not listen or react to hash changes whatsoever.
But!
lets say I move from localhost/sammy/#home to localhost/sammy/#home/detail/1
the hash change happens and changes right away to localhost/sammy/home/detail/1
for some reason the hash itself is ommited and the route doesn't get executed.
I sorry if I didnt explain myself better. I'm working on publishing it on a server for everyone to be able to look at it, but, unfortunately it takes time.
Meanwhile, if anyone has any idea what i can do to fix this it will be awesome!
So apparently (and it's written in the jQuery Mobile website the "initmobile" event fires as the script for jquery mobile it attached. To be able attach the event the following lines should be included before the jQuery Mobile script.
<script type="text/javascript">
$(document).on('mobileinit', function () {
$.mobile.ajaxEnabled = false;
$.mobile.hashListeningEnabled = false;
$.mobile.pushStateEnabled = false;
$.mobile.linkBindingEnabled = false;
});
then the onchangehash event in jquery mobile will be disabled.

Latency issue with Primefaces overlayPanel - loads to lazy

I am using Primefaces 3.2 with jsf 2 and glassfish 3.1.2.
I have a p:dataTable of users containing avatars of the user. Whenever the user moves the mouse over the avatar a p:overlayPanel appears with more information (lazy loaded) on the user, and disappears when the user moves the cursor away - like this:
<p:overlayPanel for="avatar" dynamic="true" showEvent="mouseover" hideEvent="mouseout" ...>
This works very well - as long as the user is "slowhanded". Whenever an user moves the cursor fast above many avatars many of the overlayPanels stay visible.
For example when the user has the cursor over the position where user avatars are displayed and uses the scroll wheel of his mouse to scroll the usertable down or up.
I believe that the overlaypanel starts to load the information dynamically (dynamic="true") from the server when showEvent="mouseover" is dispatched and displays the overlaypanel after the response from the server arrives.
This way it is not possible to detect whether the cursor is already away when the overlaypanel becomes visible - so the hideEvent="mouseout" is never dispatched.
Is there a way to make the primefaces overlaypanel appear directly on mousover, showing a loading gif and update the content into the overlaypanel when the response comes from the server.
Is this a good appraoch or does anyone know any other way to solve this nasty problem?
Thanks Pete
As my first answer is already very long and contains valid information, I decided to open a new answer presenting my final approach.
Im now using Primefaces inheritance pattern making the code alot cleaner. Also I noticed that replacing/overwriting the whole bindEvents function isnt necessary, as we can remove the old event handlers. Finally this code fixs the latest issue experienced: A hide event before ajax arrival.
PrimeFaces.widget.OverlayPanel = PrimeFaces.widget.OverlayPanel
.extend({
bindEvents : function() {
this._super();
var showEvent = this.cfg.showEvent + '.ui-overlay', hideEvent = this.cfg.hideEvent
+ '.ui-overlay';
$(document).off(showEvent + ' ' + hideEvent, this.targetId).on(
showEvent, this.targetId, this, function(e) {
var _self = e.data;
clearTimeout(_self.timer);
_self.timer = setTimeout(function() {
_self.hidden = false;
_self.show();
}, 300);
}).on(hideEvent, this.targetId, this, function(e) {
var _self = e.data;
clearTimeout(_self.timer);
_self.hidden = true;
_self.hide();
});
},
_show : function() {
if (!this.cfg.dynamic || !this.hidden) {
this._super();
}
}
});
Im sorry for the poor formatting: Eclipses fault ;)
Wow, finally after a long debuging session and testing various approaches i recognized that the problem isnt the ajax request but the event handlers itself:
.on(hideEvent, this.targetId, this, function(e) {
var _self = e.data;
if(_self.isVisible()) {
_self.hide();
}
});
As you can see, the widget is just hidden if its visible before. If your moving your mouse out too fast, now two things can happen:
The widget isnt visible at all
The animation is still going on
In this case the event is discarded and the panel stays visible. As animations are queued, one simply has to remove the if statement to fix the issue. I did this by replacing the whole bindEvents method:
PrimeFaces.widget.OverlayPanel.prototype.bindEvents = function() {
//mark target and descandants of target as a trigger for a primefaces overlay
this.target.data('primefaces-overlay-target', this.id).find('*').data('primefaces-overlay-target', this.id);
//show and hide events for target
if(this.cfg.showEvent == this.cfg.hideEvent) {
var event = this.cfg.showEvent;
$(document).off(event, this.targetId).on(event, this.targetId, this, function(e) {
e.data.toggle();
});
}
else {
var showEvent = this.cfg.showEvent + '.ui-overlay',
hideEvent = this.cfg.hideEvent + '.ui-overlay';
$(document).off(showEvent + ' ' + hideEvent, this.targetId).on(showEvent, this.targetId, this, function(e) {
var _self = e.data;
if(!_self.isVisible()) {
_self.show();
}
})
.on(hideEvent, this.targetId, this, function(e) {
var _self = e.data;
_self.hide();
});
}
//enter key support for mousedown event
this.bindKeyEvents();
var _self = this;
//hide overlay when mousedown is at outside of overlay
$(document.body).bind('mousedown.ui-overlay', function (e) {
if(_self.jq.hasClass('ui-overlay-hidden')) {
return;
}
//do nothing on target mousedown
var target = $(e.target);
if(_self.target.is(target)||_self.target.has(target).length > 0) {
return;
}
//hide overlay if mousedown is on outside
var offset = _self.jq.offset();
if(e.pageX < offset.left ||
e.pageX > offset.left + _self.jq.outerWidth() ||
e.pageY < offset.top ||
e.pageY > offset.top + _self.jq.outerHeight()) {
_self.hide();
}
});
//Hide overlay on resize
var resizeNS = 'resize.' + this.id;
$(window).unbind(resizeNS).bind(resizeNS, function() {
if(_self.jq.hasClass('ui-overlay-visible')) {
_self.hide();
}
});
};
Execute this code on load and the issue should be gone.
As your replacing the js code nevertheless, you can use this oppurtunity to implement quite a nice feature. By using timeouts in the event handlers one can easily implement a little delay not just improving usability (no more thousands of popups appear) but also reducing network traffic:
$(document).off(showEvent + ' ' + hideEvent, this.targetId).on(showEvent, this.targetId, this, function(e) {
var _self = e.data;
_self.timer = setTimeout( function(){
if(!_self.isVisible()) {
_self.show();
}
}, 300);
})
.on(hideEvent, this.targetId, this, function(e) {
var _self = e.data;
clearTimeout(_self.timer);
_self.hide();
});
Ofcourse you can use a global variable to control the delay time. If you want a more flexible approach youll have to overwrite the encodeScript method in the OverlayPanelRender to transmit an additional property. You could access it then with _self.cfg.delay. Notice though that youll have to replace the component model OverlayPanel too providing it with an extra attribute.
At the same time I thank you for this brilliant solution I take the opportunity to update it for Primefaces 5.2. In our application the code broke after that upgrade.
Follows the updated code for Primefaces 5.2:
PrimeFaces.widget.OverlayPanel.prototype.bindTargetEvents = function() {
var $this = this;
//mark target and descandants of target as a trigger for a primefaces overlay
this.target.data('primefaces-overlay-target', this.id).find('*').data('primefaces-overlay-target', this.id);
//show and hide events for target
if(this.cfg.showEvent === this.cfg.hideEvent) {
var event = this.cfg.showEvent;
this.target.on(event, function(e) {
$this.toggle();
});
}
else {
var showEvent = this.cfg.showEvent + '.ui-overlaypanel',
hideEvent = this.cfg.hideEvent + '.ui-overlaypanel';
this.target
.off(showEvent + ' ' + hideEvent)
.on(showEvent, function(e) {
clearTimeout($this.timer);
$this.timer = setTimeout(function() {
$('.ui-overlaypanel').hide();
$this.hidden = false;
$this.show();
}, 500);
})
.on(hideEvent, function(e) {
clearTimeout($this.timer);
$this.timer = setTimeout(function() {
// don't hide if hovering overlay
if(! $this.jq.is(":hover")) {
$this.hide();
}
}, 100);
});
}
$this.target.off('keydown.ui-overlaypanel keyup.ui-overlaypanel').on('keydown.ui-overlaypanel', function(e) {
var keyCode = $.ui.keyCode, key = e.which;
if(key === keyCode.ENTER||key === keyCode.NUMPAD_ENTER) {
e.preventDefault();
}
})
.on('keyup.ui-overlaypanel', function(e) {
var keyCode = $.ui.keyCode, key = e.which;
if(key === keyCode.ENTER||key === keyCode.NUMPAD_ENTER) {
$this.toggle();
e.preventDefault();
}
});
};
I also added an extra feature which allows the user to move the mouse over the overlay without hiding it. It should hide when you move the mouse out of it then which I accomplished through:
<p:overlayPanel .... onShow="onShowOverlayPanel(this)" ...>
function onShowOverlayPanel(ovr) {
ovr.jq.on("mouseleave", function(e) {
ovr.jq.hide();
});
}
Hope you enjoy!
It's been a long time, but in case anyone bumps into this problem, a showDelay attribute was added to the overlayPanel to solve this problem starting from Primefaces 6.2. However, it is not in the official documentation for some reason.

Resources