Así que quiero usar this desde una función externa dentro de una función de éxito de ajax. Traté de aplicar estas soluciones, pero de alguna manera no puedo hacer que funcione.
// Submit vote on submit $('.vote-choice-div').on('click', function(event){ event.preventDefault(); // bind the clicked object this.submit_vote.bind(this); // so I have to bind the element to use it in the ajax function? // fire ajax submit_vote(this.id, this); }); // AJAX for posting function submit_vote(vote) { $.ajax({ url : "submit-vote/", headers: {'X-CSRFToken': csrftoken}, type : "POST", data : { vote : vote }, success : function(data) { if(data.status === 1){ console.log(this) // can't access the initial clicked element }TypeError no capturado: no se pueden leer las propiedades de undefined (leyendo 'bind')
Tienes dos problemas (y un argumento sin sentido).
submit_vote es global, no una propiedad del elemento. Para acceder a él, no usas this .bind devuelve una nueva función. No muta el existente.submit_vote solo acepta un argumentoAsi que:
const localSubmitVote = submit_vote.bind(this) localSubmitVote(this.id); Sin embargo ... bind solo es útil si va a almacenar una función para poder pasarla o usarla varias veces.
No estás haciendo eso, solo lo estás llamando una vez, así que usa call
submit_vote.call(this, this.id); Sin embargo ... submit_vote no es un método. No es sensato diseñarlo para usar this en primer lugar. Entonces, el mejor enfoque aquí es rediseñarlo para usar solo el segundo argumento que estaba pasando antes.
function submit_vote(vote, element) { $.ajax({ // ... success: function(data) { if (data.status === 1) { console.log(element); } } }); }y
submit_vote(this.id, this)