Javascript Function call with parameter

Asked

Viewed 84 times

0

I need to call a function in Javascript where one of its parameters is a function.
In this case, how do I pass parameters within the function call?
Ex: (Function to be called first:

function getWS(data, success) {
    $.ajax({
        type: 'GET',
        url: 'MinhaUrl',
        data: data,
        async: false,
        crossDomain: true,
        dataType: 'json',
        success: success,
        error: error,
    });
}

Function in case of success in the above call:

function preencheLista(data, lista)
{
    $.each(data, function (i, item) {
        lista.push({ "id": item.id, "nome": item.nome })
    });
}

Calling for:

//Aqui que está minha dúvida. Como passar data e marcas para esta função)
var marcas = [];
getWS(data, preencheLista(data, marcas));
  • The biggest problem is you want to use synchronous ajax. You should only manipulate the list of brands from within the successful ajax callback.

1 answer

1


For the proper effect you can use the function $.proxy() jquery!
This function takes a function and returns a new one that will always have a particular context.

To be more concrete see the example of your code working on jsfiddle

var url = 'https://jsonplaceholder.typicode.com/posts';

var getWS = function(data, success) {
  $.ajax({
    type: 'GET',
    url: url,
    data: data,
    //async: false, //deprecado
    crossDomain: true,
    dataType: 'json',
    success: success,
    //error: error,
  });
}

var preencheLista = function(data, lista) {
  $.each(data, function(i, item) {
    lista.push({
      "id": item.id,
      "nome": item.title
    }) // alterado item.nome para item.title pois o objecto de retorno nao possui o atributo nome
  });
}

var marcas = [];

getWS({}, $.proxy(function(data) {
  preencheLista(data, marcas);
  
  //adiciona o resultdado a lista no html para visualização
  $(marcas).each(function(i, item) {
    $("ul").append(`<li>${item.id} - ${item.nome}</li>`)
  });
  
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <!-- Esapaco reservado para listagem do resultado-->
</ul>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.