【问题标题】:How do you deal with ASP.NET server callbacks within JavaScript objects?您如何处理 JavaScript 对象中的 ASP.NET 服务器回调?
【发布时间】:2009-05-17 01:17:41
【问题描述】:

我在使用服务器回调到 JavaScript 中的对象内的 Web 方法时遇到问题...

function myObject() {
     this.hello = "hello";
     var id = 1;
     var name;

     this.findName = function() {
          alert(this.hello); //Displays "hello"
          myServices.getName( id, this.sayHello );
     }

     this.sayHello = function(name) {
          alert(this.hello); //Displays null <-- This is where I'm confused...
          alert(name); //Displays the name retrieved from the server
     }

     this.findName();
}

因此,当创建新的myObject 时,它会找到名称,然后在找到名称后调用sayHello

服务例程工作并返回正确的名称。

问题是从服务器返回名称并调用 this.sayHello 后,它似乎不在同一个对象中(没有引用我们在查找时所在的 myObject名称)因为this.hello 给出了null...

有什么想法吗?

【问题讨论】:

    标签: asp.net javascript web-services oop


    【解决方案1】:

    这不是网络服务问题。这是标准的 javascript 功能。在回调函数中,对“this”的引用变成了对全局范围的“window”对象的引用。以下是您可以解决的方法:

    function myObject() {
         this.hello = "hello";
         var id = 1;
         var name;
         var self = this; //reference to myObject
         this.findName = function() {
              alert(this.hello); /* Displays "hello" */
              myServices.getName( id, this.sayHello );
         }
    
         this.sayHello = function(name) {
              alert(self.hello); /* Displays "hello" instead of "undefined" */
              alert(name); /* Displays the name retrieved from the server */
         }
    
         this.findName();
    }
    

    【讨论】:

      【解决方案2】:

      您必须在调用时以某种方式绑定this 对象的范围,以便稍后在同一范围内执行回调。目前,您的回调函数按照编码在全局窗口范围内执行,即this == Window。如果您使用的是框架,它们通常会提供一些传递作用域的方法,作为回调的一部分,以简化此操作。

      您还可以围绕回调参数创建一个闭包,如下所述:JavaScript Callback Scope

      【讨论】:

        猜你喜欢
        • 2012-02-15
        • 2013-09-28
        • 1970-01-01
        • 2012-02-18
        • 1970-01-01
        • 2012-10-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多