flask_moment current time refresh in browser not updating - python-3.x

Following basic setup with python3.4, jinja2, flask_moment (0.5.1), Flask(0.10.1) integration.
I am trying out the capability to simply understand the workings.
The example is nonsensical but I want to get browser to display:
firstly, the actual time in real time ("The local time is ...") continually updated in real time
secondly, the time elapsed ("That was ...").
Jinja2 code:
<p>The local time is {{ moment(current_time).format('LT', refresh=True) }}.</p>
<p>That was {{ moment(current_time).fromNow(refresh=True) }}</p>
The second line refresh works fine in the browser ("That was 1/2/3 minutes ago"), indicating all libraries working correctly, but the first line refresh doesn't work.
The method moment(current_time).format('LT', refresh=True) I thought would display the time in real time with the refresh option set to "True", but it doesn't.
Looking at browser markup, all the libraries are there and there are no errors. See markup below.
Any hints appreciated or maybe I am misunderstanding the capability?
Browser source:
<div class="container">
<div class="page-header">
<h1>Hello, Flask!</h1>
</div>
</div>
<p>The local time is <span class="flask-moment" data-timestamp="2016-01-28T12:19:20Z" data-format="format('LT')" data-refresh="60000" style="display: none">2016-01-28T12:19:20Z</span>.</p>
<p>That was <span class="flask-moment" data-timestamp="2016-01-28T12:19:20Z" data-format="fromNow(0)" data-refresh="60000" style="display: none">2016-01-28T12:19:20Z</span></p>
<script src="/static/bootstrap/jquery.min.js?bootstrap=3.3.5.7"></script>
<script src="/static/bootstrap js/bootstrap.min.js?bootstrap=3.3.5.7"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment-with-locales.min.js"></script>
<script>
moment.locale("en");
function flask_moment_render(elem) {
$(elem).text(eval('moment("' + $(elem).data('timestamp') + '").' + $(elem).data('format') + ';'));
$(elem).removeClass('flask-moment').show();
}
function flask_moment_render_all() {
$('.flask-moment').each(function() {
flask_moment_render(this);
if ($(this).data('refresh')) {
(function(elem, interval) { setInterval(function() { flask_moment_render(elem) }, interval); })(this, $(this).data('refresh'));
}
})
}
$(document).ready(function() {
flask_moment_render_all();
});

This is a misunderstanding on how Flask-Moment works, probably due to my not very clear documentation.
The moment(current_time).format('LT', refresh=True) expression that you put in the Jinja template runs in the server, not the browser. In particular, the current_time variable has a fixed value that I presume you assigned in the Python code.
The result of running this expression is some Javascript code that runs on the browser. When you pass refresh=True, this Javascript code runs every minute. But while the code does run repeatedly, the rendered time is always the same, because a value for current_time was set on the server and isn't being updated. The use of auto-refresh only makes sense with one of the "dynamic" rendering options of moment.js, such as the "X secs/mins ago" format, because those change as time passes.
If you wanted to implement something like a clock, that updates the time, then you would probably need a solution that does it all in Javascript on the browser.

So it appears that according to the documentation, the refresh=true is only going to be updated every minute. Have you given it a minute to verify that it's not refreshing?
The rendered dates and times can be refreshed periodically by passing
a refresh = True argument to any of the above functions. This is
useful for the relative formats, because they are updated as time
passes. The refresh interval is fixed at one minute.
http://blog.miguelgrinberg.com/post/flask-moment-flask-and-jinja2-integration-with-momentjs

Related

Modx Get page and sorting with &sortbyTV

Ok, before anyone points me to the Modx RTFM, let me just say, that I've actually implemented this on a few sites, using getpage rather than just getresources and they have all worked according to my needs, and what those needs were was to give visitors the ability to sort a list according to a template variable.
Now in all instances I used a listbox (single select)template variable as so (in this case for rating):
1==[[$one_star]] || 1.5==[[$one_and_half]] || 2==[[$two_star]] || 2.5==[[$two_and_half]] || 3==[[$three_star]] || 3.5==[[$three_and_half]] || 4==[[$four_star]] || 4.5==[[$four_and_half]] || 5==[[$five_star]]
Now, on my current project which is days from launch, I created a template variable called "price", in which the numerical value is entered into a text field, nothing more and, for some reason, getpage doesn't return the proper output. For example on a "low to high" page the first in the list is not the lowest priced item.
here's an example of the call. (I use getpage for pagination)
[[!getPage?
&elementClass=`modSnippet`
&showHidden=`1`
&sortbyTV=`price`
&sortdirTV=`ASC`
&element=`getResources`
&parents=`7,8,9,10,11,12`
&limit=`8`
&pageLimit=`2`
&pageVarKey=`page`
&includeTVs=`1`
&includeContent=`1`
&tpl=`store_post`
&tvPrefix=`tv.`
&cache=`0`
]]
<div class="paging">
<ul class="pageList">
[[!+page.nav]]
</ul>
</div>
and here's the template:
<div class="product_info_container">
<div class="product_name">[[+tv.product_name]]</div>
<div class="product_details">[[+tv.product_details]]</div>
<div class="product_price">price: [[+tv.price]] USD</div>
<div class="product_purchase">[[+tv.pay_button]]</div>
<div class="view_cart">[[$viewcart]]</div>
</div>
I'm on Revolution 2.2.13-pl (I tried updating to 2.2.14 but there was a php error which scared the heck outta me and until I isolate the cause, with launch looming, I'm not touching it! :P) All packages are current as well.
Any help or suggestions would be greatly appreciated because, needless to say, I'm stumped :)
p.s. I know the above getpage call is for ASC not DESC...I was just using the low to high as an example

Call javascript functions on another file from an EJS templates in Harp.js

Trying to make a website with Harp.js here. I use ejs templates, and want to store some useful javascript functions in a central file. How do I do that? I tried to use
<% include _render_util.js %>
But it does not work (seems like js file is not parsed).
Any ideas?
Thanks!
Although there are ways of making this work (sometimes), it's not something that was deliveratly built into Harp.js. Forcing this behaviour often takes time to debug and causes unexpected issues.
Here is a quick experiment I made that works (I didn't throughly test it):
helpers.ejs
I created a say_hello function that takes a name and outputs the string Hello, {name}.
<%
say_hello = function (name) {
return 'Hello, ' + name;
}
%>
index.ejs
I include helpers.ejs (the file mentioned above) in the first line and then use the function in the second line. That outputs <h1>Hello, beautiful</h1>.
<% include helpers.ejs %>
<h1><%= say_hello("beautiful") %></h1>
Example gist: https://gist.github.com/jorgepedret/816c2b3985ad12cef022
There's an open issue on GitHub discussing this issue https://github.com/sintaxi/harp/issues/272
This example is more of a hack than a recommended solution. I've seen cases where it breaks in unexpected ways.

Could the browser download remaining resource while JavaScript is running

I studied the loading behavior of Chrome/FireFox/Safari, all of them will be blocked while inline JavaScript running. Any impacts if do a rough sanning for remaining unparsed document and launch new sub resource downloading task?
Below is my testing page:
<script>
i=0;
while(i<100000)
{
i = i+1;
document.getElementById("output").innerHTML = i;
}
</script>
<img src="http://images.csdn.net/20130516/HK.jpg" />
Looking forward to learn detail of why browser block until the inline script is performed finished?
These days it's considered best to put all your Javascript includes and code just before you close the <body> tag, so that the browser can get on with downloading all the stuff in parallel that it can (e.g. images, css) in the mean time.

Problem listing documents in a CouchApp

I am in a bit of trouble as I am not able to find resources and/or tutorials that give me enough knowledge how to do this properly:
I am building a Couchapp uppon a contact database. For this I need to have a unordered list of the contacts(only the names) on the landing page. After examining this now for quite a time and examining the http://kansojs.org framework, I think I might have to ask here at Stackoverflow how this is done properly...
Here is what I ended up with (not working):
I started to setup a view (file 'views/contactslist/map.js ):
function(doc) {
if (doc.displayName) {
emit(doc.displayName, {displayname: doc.displayName});
}
};
... which basically gives me back this response:
{"total_rows":606,"offset":0,"rows":[
{{"id":"478d86edbbd94bbe627f3ebda309db7c","key":"Al Yankovic","value":{"displayname":"Al Yankovic"}},
{"id":"478d86edbbd94bbe627f3ebda30bb5cb","key":"Al-Qaeda","value":{"displayname":"Al-Qaeda"}}
]}
Afterwards, I created a new directory in the evently directory, 'contacts' and created the files "mustache.html", "data.js" and "query.json":
mustache.html:
<ul>
{{#contacts}}
<li>
<div class="name">
{{displayname}}
</div>
<div style="clear:left;"></div>
</li>
{{/contacts}}
</ul>
data.js:
function(data) {
$.log(data)
var p;
return {contacts : data.rows};
};
query.json:
{
"view" : "contactslist",
"descending" : "true"
}
Then I added
and
$("#contacts").evently("contacts", app);
to the index.html in the _attachments directory.
Watching the console in Firebug I can not see any Request/Response from CouchDB returning my vie's results, so I think it is not even requested. Where did I take the wrong turn?
data.js, query.json and mustache.html need to be in evently/contacts/_init/
_init means that this gets executed on widget initialization.
Going over this Tutorial helped a lot.

Jquery auto refresh div

Jquery auto refresh is using up a LOT of browser memory. Is there a way to stop this. I had a 2 div refreshing every 3 seconds but I moved it up to 9 and 15 seconds, It helped a little bit the longer the window stays open on my site the more memory it takes until finally the browser crashes.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" ></script>
<script>
var auto_refresh = setInterval(
function ()
{
$('#details2').load('links2.php').fadeIn("slow");
}, 15000); // refresh every 10000 milliseconds</script>
You could try to skip the load() and use $.ajax instead. I know load(); is an ajax request but I seem to recall it fetches the whole script. Try requesting a script, do your database calculations and return the data as json. I assume you're sending complete html with the data from the database request. Try this with json instead.
You'll get the data as an object, like this for example.
{"variable":"foo"}
Then you can fetch the data with a simple each statement.
$.ajax({
url: "links2.php",
type: "POST",
dataType: "json",
success: function(data){
// data here is returned as objects since it's json
$.each(data, function(key, value) {
$("#details2").empty().append(value.variable);
});
}
});
I think this shouldn't leak your memory and eventually crash your browser, even though you call it every other second or so. Give it a try and let me know how it goes.
Good luck!
Try changing it to this:
// ...
$('#details2').empty().load('links2.php').fadeIn('slow');
It may halp to explicitly tell jQuery to empty the container first, so it can free up any event handlers etc. (Though it's not clear that there would be any handlers in there ...)
edit — actually never mind; I checked the jQuery sources and it looks like calling .html() (which load() does, I'm pretty sure) seems to always call empty() first anyway.
Although an answer has been approved but I should tell you that. I had the same problem.
I found the problem in src of JQuery file. I used the JQuery site url as my source and yup it increased my computer usage to 99%. But then I downloaded the whole JQuery Script and saved it in my website directory, I used that in my source and then there was no problem with computer usage or memory. Try that too..

Resources