I am working on a website, where url parameter gets updated based on user action, according to which I update the webpage without refreshing. Consider the scenario of E-commerce where url changes when user clicks on filters and then updated products gets displayed.
我正在一个网站上工作,其中url参数根据用户操作进行更新,根据该网站我更新网页而不刷新。考虑电子商务的场景,当用户点击过滤器然后显示更新的产品时,网址会发生变化。
Now the problem is, when user clicks on Browsers's back button the browser goes back to previous url-parameter, but page did not gets changed. I want to change the page also based on url parameter that gets changed after back button clicked.
现在的问题是,当用户点击浏览器的后退按钮时,浏览器会返回上一个url-parameter,但页面没有被更改。我想根据点击后退按钮后更改的url参数更改页面。
I have tried this solution:
我试过这个解决方案:
$($window).on('popstate', function (e) {
// Update the page also
});
The problem with this code is, this gets fired as url changes, means it does not care about if browser back button is clicked, or url is changing using the jQuery. So if I am changing url based on user interaction, the popstate callback will be called and my custom function also. To update the page I am using https requests, so http api gets called two times.
这段代码的问题是,当url发生更改时会触发此问题,这意味着它不关心是否单击了浏览器后退按钮,或者是否使用jQuery更改了url。因此,如果我根据用户交互更改url,则会调用popstate回调并调用我的自定义函数。要更新页面,我使用的是https请求,因此http api会被调用两次。
Is there any way to check if only "Back button" is clicked?
有没有办法检查是否只点击了“后退按钮”?
1 个解决方案
#1
1
I would recommend you to change your design a litle bit and trigger all content updates (the product list in your case) by listening to url changes, not only url changes caused by the back button. So instead of triggering any re-rendering on click events, let these buttons be regular link to the url that represent your content and trigger the functionality from the popstate event.
我建议您通过监听网址更改来更改您的设计并触发所有内容更新(在您的情况下为产品列表),而不仅仅是后退按钮引起的网址更改。因此,不要触发对点击事件的任何重新呈现,而是让这些按钮定期链接到代表您的内容的URL并从popstate事件触发功能。
This is how all MVVM-frameworks like Angular.js, Backbone etc are designed and meant to be used.
这就是所有MVVM框架(如Angular.js,Backbone等)的设计和使用方式。
By doing this it will also be so much easier for you to maintain the application in the long run.
通过这样做,从长远来看,您也可以更轻松地维护应用程序。
Good luck!
#1
1
I would recommend you to change your design a litle bit and trigger all content updates (the product list in your case) by listening to url changes, not only url changes caused by the back button. So instead of triggering any re-rendering on click events, let these buttons be regular link to the url that represent your content and trigger the functionality from the popstate event.
我建议您通过监听网址更改来更改您的设计并触发所有内容更新(在您的情况下为产品列表),而不仅仅是后退按钮引起的网址更改。因此,不要触发对点击事件的任何重新呈现,而是让这些按钮定期链接到代表您的内容的URL并从popstate事件触发功能。
This is how all MVVM-frameworks like Angular.js, Backbone etc are designed and meant to be used.
这就是所有MVVM框架(如Angular.js,Backbone等)的设计和使用方式。
By doing this it will also be so much easier for you to maintain the application in the long run.
通过这样做,从长远来看,您也可以更轻松地维护应用程序。
Good luck!