How to set querystring or parameters dynamically with iron-router? - meteor

I've seen this thread on how to append/modify query parameters without duplicating, but I can't make it work.
I have a page in my Meteor application that lists items and allows filtering. I would like the filtering to be URL-based, so every change to a filter should reflect in the URL.
I use iron-router to then update the subscription accordingly.
For some reason, I can't modify the querystring though. This code doesn't trigger any action if called from a Template.templateName.events(...):
# valuePairs = ["foo=bar", "bar=foo"]
newUrl = Router.current().route.path {}, { query: valuePairs.join('&') }
Router.go newUrl
But if I call Router.go(newUrl) from the commandline, the expected result happens, i.e. the URL updates.
Is there another, preferred method to modify the query?
If not, how can I make above code work?
UPDATE - I just found that after running the event, if I go back in my browser history I can see the correct URL. It looks like something (?) triggers another page load to go back to original page.

Just based on
if I go back in my browser history I can see the correct URL
Do you suppress the actual link event? An <a href='#'> would flip flop you right back.
Template.tempyTheTemplate.events({
'click awesomeButton': function() {
// URL stuff
Router.go(magicURL);
return false; // <-- suppresses the event
}
});

Related

"Just Links" Event firing after "History Change" event

Google Tag Manager (GTM) has a built in trigger called "Just Links". In my VueJS application, using Vue Router, GTM fires a "History Change" event before firing the "Just Links" trigger.
(the "History Change" event has nothing to do with page view events)
Because of this, the Page Path GTM data-layer variable, which is supposed to be the path that the event was triggered on, is the same value as the Click URL GTM data-layer variable, which is the href value in the <a/> tag.
For instance:
User is on /support
User clicks on link to /about
Vue Router update browsers history
History Change event fires and updates all the internal values of Google Tag Manager data layer (including location and page path)
"Just Links" event fires, Page Path and Click URL values are now both /about
I'm assuming GTM/Google Analytics have some type of built in deferment strategy in place to not interfere with other things running on the main Javascript thread. So Vue Router changes routes (hence triggering the history change) before GTM/Google Analytics fire the "Just Links" trigger event.
(Strangely enough, when you use the built in Click - All Elements in GTM, the events fire in the right order.)
Has anyone else encountered this issue and come up with any type of solution? There might be a solution with just using Click - All Elements but that by default doesn't traverse the DOM tree with <a/> and strip the href for the Click URL value, which means extracting the href value on nested elements within an <a/> doesn't work. However, Just Links does do this.
Thanks!
You can look at tag firing priority. Adjust the click tag to have higher priority than the tag that's dependent on the history change trigger.
I just ran into this problem due to a site update. Instead of switching all of my "Just Links" to "All Elements" and dealing with the many headaches, I created a new Variable to reference for the page path instead of the built-in "Page Path" Variable. This Variable is basically storing what "gtm.linkClick" now treats as the previous page path because of the History Change. I'm just at beginner-level JS, so I'm sure there is a better way to write the code, but it works.
The first step is to create a new Custom HTML Tag (name it whatever you want) set to fire on All Pages and History Changes. The Tag will first attempt to store the current page path into Session Storage, or fallback to a cookie if Session Storage is not accessible. I used the {{JS - setCookie}} Variable method that was created by Simo Ahava to set cookies. There is a 2 second delay before writing the page path to storage, which is plenty of time for the "Just Links" Trigger to fire and receive the "correct" value before it is overwritten on the next pageview or history change. I gave the sessionStorage and cookie the same name "gtm.truepage".
Custom HTML Tag
<script>
function truePage() {
try {
var page = document.location.pathname;
var storage = window.sessionStorage;
if(storage) {
setTimeout(function() {
storage.setItem("gtm.truepage", page);
},2000);
} else {
setTimeout(function() {
{{JS - setCookie}}("gtm.truepage",page,1800000,"/",window.location.hostname);
},2000);
}
} catch (e) {
}
}
truePage();
</script>
Custom HTML Tag Screenshot
1st Party Cookie Variable
The next step is to create a new 1st Party Cookie Variable named "gtm.truepage". This Variable will be used as a reference for the Custom Javascript Variable. Therefore, if you change the name, you will also need to change the name in the next part.
Cookie Variable Screenshot
Custom Javascript Variable
The final step is to create a Custom Javascript Variable (whatever name you want) that you will use for your "Clicks - Just Links" Trigger. The script will first attempt to retrieve the page path that was set by the Custom HTML Tag from Session Storage and then try the 1st Party Cookie Variable.
function() {
return window.sessionStorage.getItem('gtm.truepage') || {{gtm.truepage}};
}
Custom Javascript Variable Screenshot
You can add an after hook to your router to create a custom path variable like this:
router.afterEach((to) => {
window.vuePath = to
}
Then in Google Tag Manager create a new User-Defined Variable with the JavaScript Variable type called Vue Path. Set Global Variable Path to window.vuePath.
Now you can use Vue Path instead of Page Path in your Triggers to get the correct page path.

algolia wordpress autocomplete

I'm trying to tweak the WordPress plugin https://github.com/algolia/algoliasearch-wordpress to suit our needs. What we want to be able to do is have a search result that will load the data up in the same page.
I have my WordPress posts and its data being indexed successfully. I have added a search box to the page, and autocomplete is being fired.
Out of the box, the WordPress plugin template wraps the result in an anchor tag and assigns it the URL of the found result. When clicked, this navigates you to that post. However, what I want to do is intercept that click and load the result in the same page without navigating away.
I have removed the href from the anchor. I have also edited the supplied autocomplete.php template where the call to autocomplete:selected occurs. In there I have removed the call to navigate away by removing window.location.href.
Now I have two main issues.
1 - When the user clicks the search result I would like the input to be populate with the title of the item they clicked on. I added this in the autocomplete:selected callback by adding $searchInput[0].value = suggestion.post_title. Which seems to change the value of the input correctly, but as soon as I click away from the input, it is re-set back to the original typed value. So if I type 'may' and click the result 'mayonnaise', the result data can be accessed but the input returns back to 'may'. My function looks this:
/* Instantiate autocomplete.js */
var autocomplete = algoliaAutocomplete($searchInput[0], config, sources)
.on('autocomplete:selected', function (e, suggestion) {
console.log(suggestion);
autocomplete.autocomplete.close();
});
2 - It seems that the autocomplete dropdown does not hide when the user clicks away. To resolve this i've had to use what I think is a bit of a nasty hack with jQuery. I was wondering if this is really required? My code just below the autocomplete:selected call looks like this:
jQuery('body').on("click", function(event){
if (!jQuery(event.target).closest($searchInput[0]).length) {
autocomplete.autocomplete.close();
}
});
Found some answers to my questions.
1 - In order to populate the input with the title of the selected search result I added a call to the setVal method of the autocomplete object. I'[m still not sure why this is required.
/* Instantiate autocomplete.js */
var autocomplete = algoliaAutocomplete($searchInput[0], config, sources)
.on('autocomplete:selected', function (e, suggestion) {
autocomplete.autocomplete.setVal(suggestion.post_title);
});
2 - It looks like the config of the autocomplete object uses the value of WP_DEBUG in order to set the debug value. The options available for the autocomplete component can be found here https://github.com/algolia/autocomplete.js#options. This lead me to find that when debug is set to true, the autocomplete box does not hide on selection. This is to allow for easier debugging and styling of the component.

FlowRouter without page reload

I am following this example https://kadira.io/academy/meteor-routing-guide/content/rendering-blaze-templates
When I click on my links the whole page is being reloaded. Is there any way to load only the template part that is needed and not the whole page?
Edit: Also I noted another problem. Everything that is outside {{> Template.dynamic}} is being rendered twice.
Here is my project sample. https://github.com/hayk94/UbMvp/tree/routing
EDIT: Putting the contents in the mainLayout template and starting the rendering from there fixed the double render problems. However the reload problems happen because of this code
Template.mainLayout.events({
"click *": function(event, template){
event.stopPropagation();
console.log('body all click log');
// console.log(c0nnIp);
var clickedOne = $(event.target).html().toString();
console.log('This click ' + clickedOne);
//getting the connID
var clientIp = null // headers.getClientIP(); // no need for this anymore
var clientConnId = Meteor.connection._lastSessionId;
console.log(clientIp);
console.log(clientConnId);
Meteor.call("updateDB", {clientIp,clientConnId,clickedOne}, function(error, result){
if(error){
console.log("error", error);
}
if(result){
}
});
}, // click *
});//events
Without this event attached to the template the routing works without any reloads, however as soon as I attach it the problem persists.
Do you have any ideas why this code causes such problems?
EDIT 2 following question Rev 3:
event.stopPropagation() on "click *" event probably prevents the router from intercepting the click on link.
Then your browser performs the default behaviour, i.e. navigates to that link, reloading the whole page.
EDIT following question Rev 2:
Not sure you can directly use your body as BlazeLayout target layout.
Notice in the first code sample of BlazeLayout Usage that they use an actual template as layout (<template name="layout1">), targeted in JS as BlazeLayout.render('layout1', {});.
In the tutorial you mention, they similarly use <template name="mainLayout">.
That layout template is then appended to your page's body and filled accordingly. You can also change the placeholder for that layout with BlazeLayout.setRoot() by the way.
But strange things may happen if you try to directly target the body? In particular, that may explain why you have content rendered twice.
Original answer:
If your page is actually reloaded, then your router might not be configured properly, as your link is not being intercepted and your browser makes you actually navigate to that page. In that case, we would need to see your actual code if you need further help.
In case your page does not actually reload, but only your whole content is changed (whereas you wanted to change just a part of it), then you should make sure you properly point your dynamic templates.
You can refer to kadira:blaze-layout package doc to see how you set up different dynamic template targets in your layout, and how you can change each of them separately (or several of them simultaneously).
You should have something similar in case you use kadira:react-layout package.

Update count for external link

I have a Meteor app for storing my bookmarks. To do that there is a Links collection with a count attribute. Every time I click the bookmark, the external site must be visited, but also the count must be increased with 1, so I can sort the bookmarks with the most visited at the top.
So now I have a link with the info in it:
{{title}}
Should I use a template instead, update the count and do a Router.go to the external site?
A little modification:
{{title}}
Then you could use:
Template.body.events({
'click a.tracked' : function(e) {
var href = $(e.currentTarget).attr('href');
ClickedLinks.insert({href: href, when: new Date()});
}
});
Where ClickedLinks is a collection. The main idea is that we track all click events on meteor body as a catch-all since everything is rendered in the body anyway even if it's in another template.. everything still winds up getting rendered there. Then we try to depend on events propagation to do our magic.
Here it is in action:
http://meteorpad.com/pad/Wtz6autqgCDEaJTLw/Leaderboard

How do I add a hash to URL in meteor iron-router?

I have a Meteor app using iron-router which displays rosters in tabs (example here). I would like the URL to include a hash that depends on which tab is showing, ie. http://example.com/myrosters#first.
I have event code like:
Template.roster.events({
'mousedown .nav-tabs li a': function (evt) {
# want to set the URL here
}
});
How do I set the URL here to include a hash, without actually triggering an unnecessary page reload? (I believe Router.go() would trigger a page reload.)
Thanks!
If the path stays the same then it seems go doesn't reload the page.
Router.go(window.location.pathname+"#test3")
When I execute the above, I see no activity in the network tab of the developers console, so I think this should work for your purposes.
Instead of Router.go You Can Use Router.url:
Router.url('yourrouterpathname', {_id: id}, {query: 'q=s', hash: 'hashFrag'});

Resources