Javascript Object Event Handler Scope, best practice(s)? -
i'm writing javascript module provides form submit.
while writing it, ran seems classic scope problem.
i want submit()
method make ajax call , use object method handle success , fail of call. since submit()
event handler, this
no longer set flagbox
object. thus, no longer have access flagbox.showsuccess()
or flagbox.showfail()
.
at first, looking way set object-wide self reference, call self.showsuccess()
.
for now, i'm using jquery.proxy()
set context of handler.
i thought implementing pub/sub pattern or attaching method event.data
.
i'm curious other solutions out there, , if there 'best practices' haven't 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 = 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!
you can bind success/failure methods object this. way success/failure methods called object's context.
(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 = 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);
Comments
Post a Comment