In the express server I have this.
app.dynamicHelpers({
dynamicValue: function(req, res) {
console.log("returning a new value");
return parseInt(Math.random() * 100);
}
});
In the client I have this.
setInterval(function() {
alert(<%= dynamicValue %>);
}
,1000);
So every second, a new number should be shown.
But that's not what happens. When the page loads a new number is generated, but the number that the client sees is always the same unless the page is reloaded.
How can this be changed to do what it's supposed to?
You are mixing server code and client code up here. The statement <%= dynamicValue %>
renders the value into a script on the page:
setInterval(function() {
alert(<%= dynamicValue %>);
}
,1000);
becomes
setInterval(function() {
alert(82.9090561);
}
,1000);
This script is later interpreted by the browser. The browser has no access to the "server script code base".
In order to make this work on the client, you need to include the particular script that creates a random number on the page:
<script type="text/javascript" src="dynamic.js" />
<script type="text/javascript">
setInterval(function() {
alert(smth.dynamicValue());
}
,1000);
</script>