Search code examples
marko

markojs data variable access in client side javascript


i am setting array of json objects into data variable like this data.journeyDetail = detail; in marko file i need to access it inside javascript block and for each record need to print FullName from the object. how to do this?

server side code:

 data.journeyDetail = detail;
 data.author = "najam";
 this.body = marko.load("./views/journeyDetail.marko").stream(data);

marko file(client side)

    <script>
    console.log("author=$data.journeyDetail.length");
    var length = $data.journeyDetail.length;
    var recs = $data.journeyDetail;
    console.log("len=", length);
    console.log("array=", array);
    for(var i=0; length; i++){
      console.log("counter=", recs[i].origin);
    }

   </script>

when page is rendering its giving javascript error and line that has error have invalid assignment var recs = [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]; console.log("len=", length);


Solution

  • You'll want to serialize the template data to the page using JSON.stringify(...). This will allow the code within your script to access the data that was first available when the template was rendered. Keep in mind, that your data.journeyDetail data cannot have circular references because this will cause error to be thrown in JSON.stringify(...). You might want to use Array map function to transform the data in the array if you don't need all of the information when your script code runs.

    You'll want to use:

    <script>
    console.log("author=$data.journeyDetail.length");
    var length = $data.journeyDetail.length;
    var recs = ${JSON.stringify(data.journeyDetail)};
    console.log("len=", length);
    console.log("array=", array);
    for(var i=0; length; i++){
      console.log("counter=", recs[i].origin);
    }
    </script>
    

    The only change was this line:

    var recs = ${JSON.stringify(data.journeyDetail)};