【问题标题】:Javascript: How to access object member from event callback functionJavascript:如何从事件回调函数访问对象成员
【发布时间】:2010-12-03 09:48:18
【问题描述】:

我在试图找出我的对象设计出了什么问题时遇到了一些问题。

var comment = function(){
var textarea = null;
$(document).ready( init );

function init()
{
    $('.reply').click( comment.reply_to );
    this.textarea = $('.commentbox textarea');
    console.log( this.textarea );   // properly shows the textarea element
    console.log( textarea );        // outputs null
}

function set_text( the_text )
{
    console.log( textarea );        // outputs null
    console.log( this.textarea );   // outputs undefined
    textarea.val( the_text );
}

return {
    reply_to: function()
    {
        console.log( this );            // outputs the element who fired the event
        set_text( 'a test text' );      // properly gets called.
    }
};
}();

当文档完全加载时,会自动调用 init() 并初始化对象。我必须注意 textarea 成员正确地指向所需的元素。 点击事件附加到“回复”按钮,因此无论何时用户点击它都会调用 reply_to() 函数。

所以,这是我不明白的: * 什么时候使用“this”是安全的?从 reply_to() 中使用它不是,因为似乎上下文设置为调用者元素。 * 为什么我可以从reply_to 调用“set_text()”,但不能访问“textarea”成员? * 我应该怎么做才能从 reply_to() 访问“textarea”成员(这是一个事件回调)?

【问题讨论】:

    标签: javascript jquery callback object


    【解决方案1】:

    由于在这些处理程序中上下文会发生变化,因此最简单的方法是保留对所需上下文的引用,我个人更喜欢self。这是另一种格式:

    var comment = function(){
        this.textarea = null;
        var self = this;
        $(document).ready( init );
    
        function init()
        {
            $('.reply').click( reply_to );
            self.textarea = $('.commentbox textarea');
        }
    
        function set_text( the_text )
        {
            self.textarea.val( the_text );
        }
    
        function reply_to() {
          set_text( 'a test text' );
        }
    }();
    

    You can test it here。诚然,虽然我不确定你想要完成什么。您正在尝试返回 reply_to 函数,但在 init() 就绪处理程序中自行绑定它......所以您可以立即绑定它(如上所示),或者将其更改并返回您想要在其他地方绑定的内容。

    【讨论】:

    • 我退回它是因为我希望它是公开的。虽然我没有测试是否将它用作回调它需要公开......我会测试它
    • 好的,不需要公开。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多