jack blank jack blank - 27 days ago 8
Node.js Question

Trying to access ejs array in a js file

I send info to the client that contains an array and I only show 3 elements of the array because I want to have a pagination effect. I wanted to write the pagination code in a js file

in file.js

$(function(){
$(".pageLinks a").on("click", function(e){
e.preventDefault();
var pageNum = $(this).attr("id")
var test = JSON.stringify(populated) // I wanted populated to be the array from node
//doesn't have to have the stringify part
// I know I can't do this prob bec. it's not in an ejs file but I wanted something like that
console.log(test)

})
})


I'm able to access it in the ejs file

<% var index = Math.floor( populated.reviews.length /3)%>
<div class = "pageLinks">
<%for(var i = 0; i < index; i++){%>
<a href= "<%=i + 1%>" id = "<%=i%>"><%= i + 1 %> </a>
<%}%>
</div>
</div> <!--reviewSide-->

Answer

You're right, you can't get to the raw object in the (static) js file in the same way.

However, you can populate it to a global variable in your ejs file like this:

<script type="text/javascript">
    var populated = <%-JSON.stringify(populated)%>;
</script>

which you can then either check for in the click handler like this:

$(function(){
$(".pageLinks a").on("click", function(e){
    e.preventDefault();
    var pageNum = $(this).attr("id")
    if (typeof(populated) != "undefined"){  
        // you want to check to make sure this exists before trying to use
        // it, just in case someone manages to click a page link before the
        // code in your .ejs file has run. 
        var test = JSON.stringify(populated) 
        console.log(test)
    }
})
})

...or pass to the external file.js when you load, as long as you're exposing something to the global scope that it can call. Your current script wraps everything in an anonymous function, but you could wrap it in a named function like this:

.ejs file:

<script type="text/javascript">
    initialiseMyAwesomeFunction( <%-JSON.stringify(populated)%> );
</script>

.js file:

function initialiseMyAwesomeFunction(populated){
     $(function(){
         $(".pageLinks a").on("click", function(e){
            e.preventDefault();
            var pageNum = $(this).attr("id")

            var test = JSON.stringify(populated) 
            console.log(test)
         })
     })
}
Comments