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!
source share