【问题标题】:jquery, simple-inheritance and 'this'jquery,简单继承和'this'
【发布时间】:2011-04-29 08:41:07
【问题描述】:

所以我正在尝试将 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 调用中访问对象吗?

【问题讨论】:

  • 一定要使用继承吗?也许您必须在某处存储对 var 中调用的每个对象的引用

标签: javascript jquery ajax inheritance


【解决方案1】:

只需使用闭包(将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】:

    你不能在 getJSON 调用之前将 this 的值存储在 do_something 中的一个变量中吗:

    var currentpane=this;

    【讨论】:

    • 是的 - 这正是解决方案! (我一点击提交就意识到了,但不允许回答我自己的问题......)谢谢!
    【解决方案3】:

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

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

    现在你可以扩展这个类并使用它的绑定方法来创建回调

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      • 1970-01-01
      • 2012-01-27
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 2019-04-26
      相关资源
      最近更新 更多