jquery,简单继承和'this'

时间:2011-04-29 08:41:07

标签: javascript jquery ajax inheritance

所以我试图将javascript用于'简单继承'(根据http://ejohn.org/blog/simple-javascript-inheritance/)。为了“简化”事物,我的想法是创建对象并将它们附加到元素上,以便我可以对它们进行操作;

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
        });
    }
});

我会有一些像

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

不幸的是,在ajax调用中,'this'变成了jquery对象,而不是我的Pane对象,所以我无法更新$ el / my_div(并且还使我的想法毫无意义)。任何想法如何在getJSON调用中访问对象?

3 个答案:

答案 0 :(得分:0)

在getJSON调用之前,你不能只将它的值存储在do_something中的变量中:

var currentpane = this;

答案 1 :(得分:0)

只需使用闭包(将this复制到外部的其他变量)

    ...
    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
        });
    }

另一种方法是使用jQuery $.proxy(更改函数上下文)。像这样:

     ...
     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
     }

答案 2 :(得分:0)

如果你想继承继承,你可以创建一个能够创建绑定到其实例的回调的基类,如下所示:

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

现在您可以扩展此类并使用其bind方法创建回调

// 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 ) );
    }
});