开发者

jquery, simple-inheritance and 'this'

so i'm trying to use javascript with 'simple inheritance' (as per http://ejohn.org/blog/simple-javascript-inheritance/). to "simplify" things, my idea was to create objects and attach them to elements so i 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 something to $el
        });
    }
});

and i would have some html like

<div id="my_div"></div>
<script>
    var p = new Pane( $('#my_div') )
    p.do_something()
</script>

unfortunately, within the ajax call, 'this' becomes the jquery object, rather than my Pane object so i can't update the $el / my_div (and also making my idea somewhat pointless). any ideas how i can access the object within the getJSON call?


Just use a closure (copy this to other variable outside)

    ...
    do_something: function() {
        this.$el.html('doing something!');
        var that = this; //Copy 'this' to 'that'
        $.getJSON( '/somewhere.js', function(data){
            that.$el.html("..."); //use 'that' instead of 'this' here
        });
    }

Another way is to use jQuery $.proxy (which changes function context). Like this:

     ...
     do_something: function() {
         this.$el.html('doing something!');            
         $.getJSON( '/somewhere.js', $.proxy( function(data){  //Here we proxy
             this.$el.html("..."); //use 'this' normally
         }, this));  //Using 'this' as context
     }


Can't you just store the value of this in a variable within do_something, before the getJSON call:

var currentpane=this;


If you want to go with the inheritance thing, you could create a base class that is able to create callbacks that are bound to its instances like this:

var Bindable = Class.extend({
    bind: function( fn ) {
        var that = this;
        return function(){ return fn.apply( that, arguments ); };
    }
}

Now you can extend this class and use its bind method to create callbacks

// extend Bindable
var Pane = Bindable.extend({
    init: function( el ) {
        this.el = el; this.$el = $(el);
        // don't return this, it's incorrect;
        //return this;
    },

    handleData: function( data ) {
        // grab an imaginary key from the data for demo purposes
        var stuff = data.key;
        this.$el.html( stuff );
    },

    do_something: function() {
        this.$el.html('doing something!');
        $.getJSON( '/somewhere.js', this.bind( this.handleData ) );
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜