How to run a function before a template is loaded?

Hello everyone.

First of all, English is not my native language, so there may be errors in the writing of this topic. Thank you

I have a query on a topic in meteor that I can not solve because I am still very new to this area.

I am creating a project that allows to search an author in google scholar through his ID and display the data through graphics in d3plus. That’s basically it.

First I have a template that contains a search engine. In this search engine is entered a string (ID) This string is received by another template. This works well.

On the other hand I have a function that runs a scraper within the google scholar profiles and displays the data in the terminal. This scraper receives a (url) containing the string entered in the previous browser.

The problem is that I do not know how to do that when I send the string (ID), it is received by the scraper first and then load the template where these data will be displayed.

This is the code for my project.

buscador.html

<template name="buscador">
  {{#if currentUser}}
  <center>
    <div class="container centrar">
      <div class="row">
        <div class="col-md-12 col-xs-12 col-lg-12" id="sidebar"> <!--Sidebar (Vertical)-->
          <div class="input-group buscador">
            <h2 class="fuente_buscador">ID Author</h2>
            <form class="main form page">
                <input name="id_investigador" id="id_investigador" type="text" value="" placeholder="ID Investigador" class="form-control"/>
                <!-- <span class="input-group-btn">
                  <button class="btn btn-secondary" type="button">Ir!</button>
                </span> -->
            </form>
          </div>
        </div>
      </div>
    </div>
  </center>
  {{else}}
    {{> accessDenied}}
  {{/if}}
</template>

buscador.js

Template.buscador.events({
  'submit form': function(e) {
    e.preventDefault();

    var busqueda = {
      id_investigador: $(e.target).find('[name="id_investigador"]').val()
    };

    var errors = validateBusqueda(busqueda);

    if (errors.id_investigador)
      return Session.set('BusquedaError', errors);

    Meteor.call('BusquedaInsert', busqueda, function(error, result) {
      if (error)
        return throwError(error.reason);

      console.log(result.id_investigador)
      console.log("========================")
      Router.go('results', {id_investigador: result.id_investigador});
    });
  }
});

results.html


<template name="results">
  {{> sidebar}}
  {{> perfil}}
  <h3>Publicaciones</h3>
  <div class="radio"> <!--Inputs-->
    <div class="row">
      <div class="col-md-3 col-xs-6">
        <label><input type="radio" name="optradio">Campo</label>
        <label><input type="radio" name="optradio">Revista</label>
      </div>
      <div class="col-md-2 col-md-offset-7 col-xs-2 col-xs-offset-3">
        <button type="button" class="btn exportar">Exportar a CSV</button>
    </div>
    </div>
  </div>
  <center><h5>Número total de citaciones: 5457</h5></center>

  {{> tree}}

  {{> barras}}

  {{> colaboradores}}
  <script type="text/javascript">

  var fs      = require('fs');
  var request = require('request');
  var cheerio = require('cheerio');

  url = "https://scholar.google.cl/citations?user={{ id_investigador }}&hl=es";

  request(url, function(error, response, html){
    if(!error){
      var $ = cheerio.load(html);

      var id_usuario, autor, imagen_usuario, institucion, campos, titulos, citas_totales, citas_2012, indice_h_totales, indice_h_2012,
          indice_i10_totales, indice_i10_2012;

      var json = {  id_usuario: "",
                    autor : "",
                    imagen_usuario: "",
                    institucion : "",
                    campos : "",
                    titulos : "",
                    citas_totales : "",
                    citas_2012 : "",
                    indice_h_totales : "",
                    indice_h_2012 : "",
                    indice_i10_totales : "",
                    indice_i10_2012 : ""
                 };

      $('#gsc_prf_in').filter(function(){
        var data = $(this);
        autor = data.text().trim();

        json.autor = autor;
      })

      $('input[name="user"]').filter(function(){
        var data = $(this);
        id_usuario = data.val();

        json.id_usuario = id_usuario;
      })

      $('#gsc_prf_pup').filter(function(){
        var data = $(this);
        imagen_usuario = data.attr('src');

        json.imagen_usuario = imagen_usuario;
      })


      $('#gsc_prf_i').filter(function(){
        var data = $(this);
        campos = data.children().eq(3).children().eq(0).text().trim();

        json.campos = campos;
      })

      $('#gsc_prf_i').filter(function(){
        var data = $(this);
        institucion = data.children().eq(2).children().text().trim();

        //institucion = data.next().children().attr('href');

        json.institucion = institucion;
      })

      $('#gsc_a_b').filter(function(){
        var data = $(this);
        titulos = data.children().length;

        json.titulos = titulos;
      })

      /*$('.gsc_a_tr').filter(function(){
        var data = $(this);
        titulo = data.text();

        json.titulo = titulo;
      })*/

      //CITAS
      $('table[id="gsc_rsb_st"]').filter(function(){
        var data = $(this);
        citas_totales = data.children().eq(1).children().eq(1).text();

        json.citas_totales = citas_totales;
      })

      $('table[id="gsc_rsb_st"]').filter(function(){
        var data = $(this);
        citas_2012 = data.children().eq(1).children().eq(2).text();

        json.citas_2012 = citas_2012;
      })

      $('table[id="gsc_rsb_st"]').filter(function(){
        var data = $(this);
        indice_h_totales = data.children().eq(2).children().eq(1).text();

        json.indice_h_totales = indice_h_totales;
      })

      $('table[id="gsc_rsb_st"]').filter(function(){
        var data = $(this);
        indice_h_2012 = data.children().eq(2).children().eq(2).text();

        json.indice_h_2012 = indice_h_2012;
      })

      $('table[id="gsc_rsb_st"]').filter(function(){
        var data = $(this);
        indice_i10_totales = data.children().eq(3).children().eq(1).text();

        json.indice_i10_totales = indice_i10_totales;
      })

      $('table[id="gsc_rsb_st"]').filter(function(){
        var data = $(this);
        indice_i10_2012 = data.children().eq(3).children().eq(2).text();

        json.indice_i10_2012 = indice_i10_2012;
      })


    }


    fs.writeFile('./output.json', JSON.stringify(json, null, 4), function(err){
      console.log('--------------------------------')
      console.log('File successfully written! - Check your project directory for the output.json file');
    })

    console.log(json)
  })

    var sample_data = [
       {"value": 100, "name": "alpha", "group": "group 1"},
       {"value": 70, "name": "beta", "group": "group 2"},
       {"value": 40, "name": "gamma", "group": "group 2"},
       {"value": 15, "name": "delta", "group": "group 2"},
       {"value": 5, "name": "epsilon", "group": "group 1"},
       {"value": 64, "name": "diamond", "group": "group 3"},
       {"value": 100, "name": "music", "group": "group 4"},
       {"value": 30, "name": "guitar", "group": "group 4"},
       {"value": 90, "name": "bass", "group": "group 4"},
       {"value": 40, "name": "pearl", "group": "group 3"},
       {"value": 1, "name": "zeta", "group": "group 1"}
     ]

     var visualization = d3plus.viz()
       .container("#viz")
       .data(sample_data)
       .type("tree_map")
       .id(["group","name"])
       .size("value")
       .draw()

       var data = [
         {"año": '2010', "name":"alpha", "citaciones": 120},
         {"año": '2011', "name":"alpha", "citaciones": 80},
         {"año": '2012', "name":"alpha", "citaciones": 56},
         {"año": '2013', "name":"alpha", "citaciones": 62}
       ]

       var visualization = d3plus.viz()
         .container("#viz2")
         .data(data)
         .type("bar")
         .id("name")
         .x("año")
         .y("citaciones")
         .draw()

       //******************************************************************************************

       var data2 = [
         {"año": '2010', "name":"alpha", "publicaciones": 3},
         {"año": '2011', "name":"alpha", "publicaciones": 2},
         {"año": '2012', "name":"alpha", "publicaciones": 1},
         {"año": '2013', "name":"alpha", "publicaciones": 2}
       ]

       var visualization = d3plus.viz()
         .container("#viz2-1")
         .data(data2)
         .type("bar")
         .id("name")
         .x("año")
         .y("publicaciones")
         .draw()

         // create sample dataset
         var sample_data = [
           {"name": "alpha", "size": 10},
           {"name": "beta", "size": 12},
           {"name": "gamma", "size": 30},
           {"name": "delta", "size": 26},
           {"name": "epsilon", "size": 12},
           {"name": "zeta", "size": 26},
           {"name": "theta", "size": 11},
           {"name": "eta", "size": 24}
         ]

         // create list of node positions
         var positions = [
           {"name": "alpha", "x": 10, "y": 15},
           {"name": "beta", "x": 12, "y": 24},
           {"name": "gamma", "x": 16, "y": 18},
           {"name": "delta", "x": 26, "y": 21},
           {"name": "epsilon", "x": 13, "y": 4},
           {"name": "zeta", "x": 31, "y": 13},
           {"name": "theta", "x": 19, "y": 8},
           {"name": "eta", "x": 24, "y": 11}
         ]

         // create list of node connections
         var connections = [
           {"source": "alpha", "target": "beta"},
           {"source": "alpha", "target": "gamma"},
           {"source": "beta", "target": "delta"},
           {"source": "beta", "target": "epsilon"},
           {"source": "zeta", "target": "gamma"},
           {"source": "theta", "target": "gamma"},
           {"source": "eta", "target": "gamma"}
         ]

         // instantiate d3plus
         var visualization = d3plus.viz()
           .container("#viz3")  // container DIV to hold the visualization
           .type("network")    // visualization type
           .data(sample_data)  // sample dataset to attach to nodes
           .nodes(positions)   // x and y position of nodes
           .edges(connections) // list of node connections
           .size("size")       // key to size the nodes
           .id("name")         // key for which our data is unique on
           .draw()             // finally, draw the visualization!

         //******************************************************************************************

           var sample_data_2 = [
             {"value": 100, "name": "alpha", "group": "group 1"},
             {"value": 70, "name": "beta", "group": "group 2"},
             {"value": 40, "name": "gamma", "group": "group 2"},
             {"value": 15, "name": "delta", "group": "group 2"},
             {"value": 5, "name": "epsilon", "group": "group 1"},
             {"value": 64, "name": "diamond", "group": "group 3"},
             {"value": 100, "name": "music", "group": "group 4"},
             {"value": 30, "name": "guitar", "group": "group 4"},
             {"value": 90, "name": "bass", "group": "group 4"},
             {"value": 40, "name": "pearl", "group": "group 3"},
             {"value": 1, "name": "zeta", "group": "group 1"}
           ]

           var visualization = d3plus.viz()
             .container("#viz-4")
             .data(sample_data_2)
             .type("tree_map")
             .id(["group","name"])
             .size("value")
             .draw()
  </script>
</template>

results.js

– (Nothing)–

I was looking at the meteor documentation but I do not quite understand. I think the most convenient thing is to create an Oncreated object from the results template. I hope someone could help me to solve this problem.

Thank you very much to all.

There are many different ways to solve this, but a simple one to start with, is to save the result of your scraper function with Session.set('scraperData', result).

Then create a template helper like this:

Template.results.helpers({
  scraperData(){
    return Session.get('scraperData');
  }
});

This will make it so that as soon as the data is available, the template will automatically be re-rendered with the data :slight_smile:
Hope that helps

1 Like