Reputation: 397
I have ASP.NET MVC 3 + JQuery Mobile application with such structure of layout:
<body>
<div class="page" data-role="page" data-add-back-btn="true" id="page">
<div data-role="header" data-position="fixed"></div>
<div data-role="content" id="content">
@RenderBody()
</div>
<div id="footer" data-role="footer" data-position="fixed"></div>
</div>
</body>
The issue is, that event handlers binded to window stuck for several pages.
For example I have 2 pages: "Index"
and "About"
. In "Index"
I bind some handler(say console.log("index"))
on $(window).click()
event. But when I go to "About"
page - this handler is still active.
Is there any way to keep handlers only while appropriate page is active?
Upvotes: 2
Views: 588
Reputation: 397
I made small research about this issue, but didn't find anything appropriate such issue. So I've implemented solution for the discribed usecase with window events. It's creepy, but works.
In Layout:
1.Page div declaration:
<div class="page" data-role="page" data-add-back-btn="true" id="@Request.RawUrl.GetHashCode()">
...
</div>
2.Scripts:
<script type="text/javascript">
var bindEvents = [];
$(document).bind('pagehide', function (event) {
var hash = $(event.target).attr('id');
$(window).unbind('.' + hash);
});
$(document).bind('pageshow', function (event) {
var hash = $(event.target).attr('id');
bindEvents[hash]();
});
</script>
In pages:
1.Index:
<script type="text/javascript">
var hashedIndex = '@Request.RawUrl.GetHashCode()';
if (!bindEvents.hasOwnProperty(hashedIndex)) {
bindEvents[hashedIndex] = function() {
$(window).bind('click.' + hashedIndex, function() {
console.log('index');
});
};
};
</script>
2.About:
<script type="text/javascript">
var hashedAbout = '@Request.RawUrl.GetHashCode()';
if (!bindEvents.hasOwnProperty(hashedAbout)){
bindEvents[hashedAbout] = function () {
$(window).bind('click.' + hashedAbout, function() {
console.log('about');
});
};
};
</script>
And similar to other pages if needed.
In general case I agree with Gajotres: it's better to bind events to some inner containers to avoid such issues.
Upvotes: 0
Reputation: 57309
Use this kind of event binding with jQM:
$('#page').bind('click', function(e) {
});
With newer version of jQuery use .on( and .off( to bind/unbind event. $('#page') is your page.
This:
$(window).click()
will bind it to window, because jQM page is a single window event will fire every time. You also need to worry about multiple event binding, here you can find more info about this problem.
Upvotes: 1