Javascript Object Event Handler Scope, Best Practice (s)?

I am currently writing a Javascript module that basically provides a form for submission.

While writing, I came across what seems like a classic problem.

I want the submit() method to make an AJAX call and use the object method to handle success and failure of the call. Since submit() is an event handler, this no longer set to the flagBox object. This way, I no longer have access to flagBox.showSuccess() or flagBox.showFail() .

At first, I was looking for a way to set the object binding so that I could call something like self.showSuccess() .

I am currently using jQuery.proxy() to set the context of the handler.

I also thought about implementing a pub / sub template or attaching a method to event.data .

I am curious what other solutions exist, and if there are any โ€œbest practicesโ€ that I have not found.

 (function( $ ) { var FlagBox = function() {}; FlagBox.prototype = { constructor: FlagBox, init: function() { $('.flag-content-box') .on('submit', $.proxy(this.submit, this)); }, ... showSuccess: function() { console.log('success'); }, showFail: function() { console.log('fail'); }, submit: function(event) { event.preventDefault(); var that = this; formData = $(event.target).serializeObject(); $.ajax({ type:"POST", url: '/flag/add.json', data: formData, success : function(data) { that.showSuccess(); }, error : function(jqXHR, textStatus, errorThrown) { showFail(); } }); } }; var flagBox = new FlagBox(); flagBox.init(); })(jQuery); 

Thanks!

+4
source share
1 answer

You can bind success / failure methods to your object as follows. Thus, success / failure methods will always be used in the context of your object.

 (function( $ ) { var FlagBox = function() {}; FlagBox.prototype = { constructor: FlagBox, init: function() { $('.flag-content-box') .on('submit', $.proxy(this.submit, this)); }, ... showSuccess: function() { console.log('success'); }, showFail: function() { console.log('fail'); }, submit: function(event) { event.preventDefault(); var that = this; formData = $(event.target).serializeObject(); var successFn = (function(obj){ return function(){ return obj.showSuccess.apply(obj, arguments) } })(this); var failureFn = (function(obj){ return function(){ return obj.showFailure.apply(obj, arguments); } })(this); $.ajax({ type:"POST", url: '/flag/add.json', data: formData, success : successFn, error : failureFn }); } }; var flagBox = new FlagBox(); flagBox.init(); })(jQuery); 
0
source

Source: https://habr.com/ru/post/1492630/


All Articles