Execute route change before event function - meteor

I've got a list of menu items and each is an a tag. Inside those, I've got notification bubbles insides a div. When the notification div is clicked, I'd like to first follow the a tag (the hash is always to a Meteor route, using Iron Router) before it executes the click event attached to the div. Since reverse-propagation hasn't existed since the netscape days, I thought maybe that click event could store a function as a callback when the route changes? Has anyone tried to do something similar? Couldn't find anything in the Iron Router docs about it. I'm currently mitigating the problem with a few Session vars, but would like to clean it up.

Without seeing what your code is currently doing (or even better, a simplified example), I am guessing a bit at what you are trying to do. Maybe you have something like this:
<div id="bubblething">Click Me!</div>
With a click event:
'click #bubblething': function() {
// Do the bubble thing.
}
But the problem is you'd like to trigger the click event after you route but the click is happening to early. Would it be possible to change it to something more like this:
<div id="bubblething">Click Me!</div> //no <a> tag.
With the click event handling the actually routing first then moving on:
'click #bubblething': function(){
Router.go('/yourroute'); // First you route
{ ... } // Code to handle the notification bubble.
}
You may have to update your styling a bit do to the lack of am <a> tag but that should be pretty simple. The routing is handled by the click and then other things happen. You can parameterize this so that instead of calling an id you call a class and inject the route.

Related

Viewing Ractive events in browser console

I've been reading the RactiveJS docs on event management at https://ractive.js.org/get-started/tutorials/events/, and had a question around rendering of events:
Instead, the on- directive will bind a shared callback directly to the element using addEventListener when it is rendered.
Is it possible to see what the rendered event would look like? I know it won't appear within console, but it would be nice to see if there is a way of viewing an example of how a rendered event would appear.
What that portion of the tutorials meant to say is that the on-* directive doesn't render inline JS nor render on the DOM at all. It's a directive that simply signals Ractive what to do. Even if the template looks like this:
<button on-click="#global.alert( 'Activating!' )">Activate!</button>
What ends up in the DOM is a button with an event handler.
<button>Activate!</button>
Under the hood, the on-* is processed from the parsed template and is converted to something roughly similar to the following:
buttonReference.addEventListener('click', function(){
theGlobalDependingOnTheEnv.alert( 'Activating!' );
});

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.

How can I simulate a click event on an anchor tag without actually calling click or refreshing?

I am using meteor with iron router and meteors standard blaze tempting.
I have an ul set up so that when one of my li items is clicked its containing anchor tag is clicked on using the function click. The only problem is that when that a is clicked with the function it counts as another click on my li and my menu isn't toggling right.
I am wondering if there is a way to call the pathFor without actually calling a click function.
Thanks for any help!
Update, here is the code its working along with a pretty standard drop down nav. I am not sure if I can catch that event the same as a jquery event since I think it is the standard browser click event working on the [0], but I think I should be able to make a function that matches href to route and call Router.go
Template.nav.rendered = () ->
# set initial page view and take care of refeshes
currentPageHtlm = getCurrentPage(window.location.pathname)
$('#currentPage').find('span').html(currentPageHtlm)
$("li").on "click", () ->
#simulate anchor click and set currentPage session
$(this).find("a")[0].click()
Session.set 'pageName', getCurrentPage($(this).find("a").attr("href"))
currentPageHtlm = Session.get 'pageName'
$('#currentPage').find('span').html(currentPageHtlm)
# toggle nav and arrow if mobile view
if $('.smOnly').css('display') != 'none'
$('#nav').slideToggle('slow')
$('#dropArrow').toggleClass('fa-caret-square-o-down fa-caret-square-o-up')
It sounds like you're looking for a way to programatically redirect from JS rather than via UI interaction, in which case you need to use Router.go('ROUTE_NAME'), as per the docs (you can use the route name as in pathFor as an alternative to supplying the actual path).

jquery .load( ) and trigger function AFTER new content loads? just like JavaScript onload event

Using jquery, I am swapping some content in a web page by use of jquery's .load() function. I want to trigger an event immediately once the content has actually been loaded, but not before and not after. I'm up for any graceful solution! Why? In this instance, I'm doing the old "fade out, swap content, fade in" approach. My problem? I want to fade back in AS SOON AS the new content is loaded.
Caveats:
Using a callback function as in $('#object').load(url, callback) triggers as soon as .load() function successfully executes (before the content is actually loaded). Useless here.
Using a timed delay for fading back in is not a graceful solution. Very "clunky", especially for those with faster Internet connectivity.
JavaScript's onload event trigger does not work, as the element that .load() is altering has already loaded into the HTML DOM.
jquery's .ready() function also does not work, as the actual element is already loaded.
I do not want to create an onload or .ready() sub-container element, because that's a workaround for what I'm actually trying, though it might be as graceful or more.
How can I fire a function when (and only when) the new .load() content is finally loaded, just like JavaScript's onload event does? Thanks much.
EDIT As it turns out, the jquery .load() function is working flawlessly, and I'm approaching this wrong.
Once the .load() function completes successfully, it calls any "callback" function included by the programmer, just like any other jquery function that accepts a callback as one of its "arguments".
The .load() function is complete once it either errors or successfully begins the HTML replacement and loading of new content, but that is IT! The content will then take however long it takes to load, but your .load call is already complete before that. Therefore, expecting the callback to run after the .load content has loaded will only disappoint you. ;)
I hope others can learn from this just as I did, including those who thought what I thought was the case. Proof: as stated in the jquery ajax .load page, the callback is executed when the request completes, not when the load completes. Eureka. Whoops. /EDIT
Try using a different method rather than load(), I would suggesting using get(). Something like this may be more useful to you...
var jqxhr = jQuery.get(url,vars);
jqxhr.success(function(data){
# This will only be called once the remote content has been loaded in
# The data will then be stored in the data param and can be used within your site
});
jqxhr.error(function(data){
# Something went wrong, never mind lets just handle it gracefully below...
});
I hope this is a solution to your problem!
For more information see http://api.jquery.com/jQuery.get/
I have quickly created this function below that may be of help to you... its not refined!
jQuery.fn.loadNewData = function() {
var object = jQuery(this);
var jqxhr = jQuery.get(arguments[0]);
// check for success
jqxhr.success(function(data) {
// load the data in
object.html(data);
});
jqxhr.error(function(){
alert('Failed to load data');
});
}
Using this you can call how similarly to how you would call the load() function.
jQuery('#object').loadNewData(url);
I think you might be misinterpreting what you are seeing. Depending on the browser you are using you won't see the new elements in the browser if you pop up an alert in the callback because it won't rerender the DOM until you cede control back to the browser. That doesn't mean you can't grab the new elements from the DOM and start fading them in. Take the following jsfiddle: http://jsfiddle.net/ttb55/8/ in Chrome it will show the first div when the second alert is up, then fade in the second div. In IE it won't show the first div when the second alert is up, this is the state I think you are in after load during the callback, but it still works once you hit ok because everything was in the DOM as promised.
Upon reading the jQuery docs pages for jQuery.get() and jQuery.load(), the callback argument is quoted as the following:
"A callback function that is executed if the request succeeds."
Let me stress the terms "request" and "succeeds". The request may succeed, but that does not mean that the content is loaded. Same problem as .load() — the functions aren't built the way I was thinking.
If I want to trigger an event once the new content finally loads, I'll need to take a different approach.
I could use the JS onload event, and trigger it by completely replacing an HTML element (having the replaced code contain an onload property). EDIT: Note that using HTML iframe elements is pretty awful, primitive, and "clunky". I just need to find a better way to trigger a function as soon as loading the new content finishes.
Also, I could use jQuery to check the .ready() state of new content, but ("AFAIK" / as far as I know) that will only work if the checked content is a new HTML element, not a preexisting HTML element whose interior content is changed. The jQuery .ready() status of any preexisting element will (AFAIK) already be shown as "ready" despite if new content is loading. Perhaps I am wrong about this, and I would like to be corrected if so.
Unless otherwise notified, this answer will be marked as the correct one. The original question was mistaken that .load() was all I needed. Cheers!

JavaScript puzzle to solve : window.confirm = divConfirm(strMessage)

Scenario is : old site which has lots of JS code already written. If user want to change all the alert messages to new age jazzy Div based alert which are very common using JQuery, YUI, Prototype... etc.
There are mainly tree JS dialogs
1. alert
To changes this its simple we just have to write new function which will show the div popup and show the message, after that override the window.alert
function showDivAlert(strMessage){
//div popup logic and code
}
window.alert = showDivAlert;
2. prompt
This too look easy to write function to accept the string and show the text box for input value. Now as return action is based on the click of "OK" button life is easy here.
function shoDivPromp(strMessage){
//div pop up to show the text box and accept input from the user
}
window.prompt = shoDivPromp;
3. confirm
Now above two were easy to override and modify the default dialogs but there is complication with the confirm.
However default JS confirm dialog stops JS execution and when user click OK or Cancel execution is resumed by determining the return value (true/false). But if we user div popup the execution is not stopped which is problem. We can still implement the confirm but in that case we have to bind methods for OK and CANCEL case which will be attached to OK and CANCEL button. With this function signature will be like.
function newConfirm(msg, fun OkAction(), fun CancelAction)
Now this is problem that this cant help me change the confirm dialog across the site as we did with alert();
Question
I am not sure whether its possible or not to achieve but i think can be using some JS pattern. So let me know if its possible.
Now this is problem that this cant help me change the confirm dialog across the site as we did with alert();
That's correct. It's not possible to reproduce the synchronous nature of the alert/confirm/prompt functions in native JavaScript. There is the non-standard method showModalDialog which can do it using a separate pop-up document, but it's not supported by all browsers and it's generally considered highly undesirable.
So the plug-in-replacement strategy isn't going to work. You are going to have to change every place you called these methods in the rest of the script.
The usual pattern is to do it using inline anonymous functions, to preserve the local variables using a closure, eg. replace:
function buttonclick() {
var id= this.id;
if (confirm('Are you sure you want to frob '+id+'?'))
frob(id);
wipe(id);
}
with:
function buttonclick() {
var id= this.id;
myConfirm('Are you sure you want to frob '+id+'?', function(confirmed) {
if (confirmed)
frob(id);
wipe(id);
});
}
If you need this to be preserved you would need to look at a further nested closure or function.bind to do it. If you have your call to confirm in a loop things get considerably more difficult.
Obviously you also have to ensure that critical global state doesn't change whilst the confirm box is up. Usually this risk is minimised by greying out the rest of the page with an overlay to stop clicks getting through. However if you have timeouts they can still fire.
All 3 methods actually stop js execution, not just the confirm, because they're all modal dialogs. Personally, I would try to keep everything as asynchronous as possible as modal dialogs prevent interaction with the current document.
Your best bet is to use callback functions from the new confirm popup as you suggested yourself.
I'm having a hard time understanding exactly what you want to achieve. It sounds like you want to do something like the following:
Run some javascript code
Display a "confirm" box
Wait until the ok button or cancel button is clicked
Continue code when user clicks ok, return when user clicks cancel.
The reason you want to do this is that overriding the function with something that makes use of callbacks would require rewriting each section of code that uses the confirm function. If you want my advice, I would go ahead and rewrite the code so that it performs asynchronously. There's no way you can delay script execution without locking up the document which includes the OK and Cancel actions of your dialog.
if you changed the roles Alert / Prompt / Confirm. slows the execution pending user interaction to run the following code.
Overriding these functions, the code continues its execution.
To achieve this you have to modify each part of the code and work as if you were with asynchronous functions.
Then you can use any plugin for windows as sexy-alert-box, and overwrite Alert / Prompt / Confirm
The function signature would simply be:
function newConfirm(msg, okAction, cancelAction);
and would be used as:
function newConfirm(msg, okAction, cancelAction){
var ok = doWhateverPromptIsNecessary();
if (ok) {
okAction();
} else {
cancelAction();
}
}
That is, to pass function "pointers" in to a function as arguments, simply pass in the function name without the (). The function signature is the same.

Resources