Reputation: 69
I have trouble getting my head around how to call Javascript functions in a view. What I want to achieve is a HTML-Table where some fields are updated regularly based on some parameters.
So I need a function with parameters which gets the respective HTML Element and sets an interval in which the elements.innerHTML is set. So far, so good. I have this function
export default function calcActual(amount, gain, time, index) {
var td;
td = document.getElementById('ressource_' + index);
setInterval(function() {
td.innerHTML = "actual: " + Math.round(amount + (gain / 3600) * time);
}, Math.round(gain / 3600));}
in 'priv/js/views/user_assets/rou.js'
In my 'app.js' I have the following:
import { calcActual } from './views/user_assets/rou';
As far as I understood, all the code from app.js is stuffed in a module, so I just don't have any possibility to call the function directly. My next thought was to wrap the function again in app.js and call it from there.
export var Calc = {
calcActual: function(amount, gain, time, index) {
calcActualRes(amount, gain, time, index)
}
}
but I always get the error that Calc
is not defined, when trying to call the function with:
<td id="ressource_<%= index %>">
actual:<script>Calc.calcActual(
<%= amount %>,
<%= gain %>,
<%= NaiveDateTime.diff(NaiveDateTime.utc_now, ressource.updated_at) %>,
<%= index %>)
</script>
</td>
Can anyone explain, why this fails and how to get this working?
Upvotes: 1
Views: 617
Reputation: 5478
You'll need to actually import the module using require
before using it:
<script>
var calcActual = require('views/user_assets/rou');
// do your stuff with calcActual.
</script>
Just make sure that app.js
is loaded before you call require
function, otherwise it will complain require
is not defined.
Upvotes: 3