This question has already been answered:
- Loss of context call 5 responses
There is code, a piece on jquery - everything works fine (the first button), but if I click on the second button to which the event is registered using addEventListener, I lose context, that is the button, this is the ajax options object.
How then, when clicking the second button, call _.setText() from within getAjax() ?
$(function() { var _ = { initJquery: function() { var that = this; $('#one').on('click', function() { that.getAjax(); }); }, initJs: function() { $('#two')[0].addEventListener('click', this.getAjax); }, setText: function(text) { $('.update').html(text); }, getAjax: function() { var that = this; $.ajax({ url: 'txt.txt', type: 'POST', dataType: 'text' }) .done(function(resp) { console.log('this'); console.log(this); console.log('that'); console.log(that); // ΠΏΡΠΈ Π½Π°ΠΆΠ°ΡΠΈΠΈ ΠΏΠ΅ΡΠ²ΠΎΠΉ ΠΊΠ½ΠΎΠΏΠΊΠΈ Π²ΡΡ Ρ
ΠΎΡΠΎΡΠΎ // ΡΡΡ ΡΠ΅ΡΡΡ ΠΊΠΎΠ½ΡΠ΅ΠΊΡΡ ΠΏΡΠΈ Π½Π°ΠΆΠ°ΡΠΈΠΈ Π²ΡΠΎΡΠΎΠΉ ΠΊΠ½ΠΎΠΏΠΊΠΈ addEventListener that.setText(resp); }) .fail(function() { console.log("error"); }); } }; _.initJquery(); _.initJs(); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type="button" id="one" value="ΠΠ½ΠΎΠΏΠΊΠ° 1"> <input type="button" id="two" value="ΠΠ½ΠΎΠΏΠΊΠ° 2"> <div class="update"></div> Result
Thank you all, figured out. It was necessary so:
.done(function() { this.setText(resp); }.bind(this)) The final code is:
$(function() { var _ = { initJquery: function() { $('#one').on('click', function() { this.getAjax(); }.bind(this)); }, initJs: function() { $('#two')[0].addEventListener('click', this.getAjax.bind(this)); }, setText: function(text) { $('.update').html(text); }, getAjax: function() { $.ajax({ url: 'txt.txt', type: 'POST', dataType: 'text' }) .done(function(resp) { console.log('this'); console.log(this); this.setText(resp); }.bind(this)) .fail(function() { console.log("error ajax"); }.bind(this)); } }; _.initJquery(); _.initJs(); }); 