2

我有一個佈局這樣的結構ASP.NET MVC 3 + jQuery Mobile的應用:ASP.NET MVC + jQuery Mobile的事件處理程序

<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> 

的問題是,綁定到卡住幾頁窗事件處理程序。

例如我有2頁:"Index""About"。在"Index"我結合一些處理(比如console.log("index"))$(window).click()事件但是,當我去"About"頁面 - 這個處理器仍然活躍

有什麼辦法讓處理程序只有在相應的頁面是活躍

回答

0

我對這個問題做了小小的研究,但沒有找到任何合適的問題。 因此,我已經爲窗口事件實現了描述用例的解決方案。這是令人毛骨悚然,但工程。

佈局:

1.Page DIV聲明:

<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> 

在網頁:

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.關於:

<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> 

,如果需要,類似的其他網頁。

在一般情況下,我同意Gajotres:最好將事件綁定到某些內部容器以避免此類問題。

1

使用?這類事件與JQM結合:

$('#page').bind('click', function(e) { 

}); 

使用jQuery的較新版本的使用。對(和.off(綁定/解除綁定事件$( '#頁')是你的頁面

釷。是:

$(window).click() 

將它綁定到窗口,因爲jQM頁面是單個窗口事件,每次都會觸發。 你還需要擔心多個事件綁定,here你可以找到更多關於這個問題的信息。

+0

不幸的是,我需要處理確切的窗口事件(滾動),所以綁定到一些內部容器是不可能在我的應用程序的上下文中。 –

+0

然後你需要找到一個方法,jQM web應用程序是一個單一的窗口應用程序。你用窗口事件(滾動)做什麼? – Gajotres

+0

無盡的滾動。我試過基於iscroll的插件,但它們在某些平臺上有點bug。現在我正在尋找無需使用窗口對象來實現無限滾動的方式 - 希望它能幫助解決這個問題。 –