javascript - jquery, simple-inheritance and 'this' -
so i'm trying use javascript 'simple inheritance' (as per http://ejohn.org/blog/simple-javascript-inheritance/). "simplify" things, idea create objects , attach them elements can operate on them;
var pane = class.extend({ init: function( el ) { this.el = el; this.$el = $(el); return this; }, do_something: function() { this.$el.html('doing something!'); $.getjson( '/somewhere.js', function(data){ // write $el }); } });
and have html like
<div id="my_div"></div> <script> var p = new pane( $('#my_div') ) p.do_something() </script>
unfortunately, within ajax call, 'this' becomes jquery object, rather pane object can't update $el / my_div (and making idea pointless). ideas how can access object within getjson call?
just use closure (copy this
other variable outside)
... do_something: function() { this.$el.html('doing something!'); var = this; //copy 'this' 'that' $.getjson( '/somewhere.js', function(data){ that.$el.html("..."); //use 'that' instead of 'this' here }); }
another way use jquery $.proxy
(which changes function context). this:
... do_something: function() { this.$el.html('doing something!'); $.getjson( '/somewhere.js', $.proxy( function(data){ //here proxy this.$el.html("..."); //use 'this' }, this)); //using 'this' context }
Comments
Post a Comment