你能解释一下为什么这个 jQuery 代码有效吗?

发布于 2024-12-08 20:51:07 字数 1048 浏览 0 评论 0原文

我知道它有效。我已经成功实施了。

$("#vehicle_application_product_id").autocomplete({
      minLength: 2,
      source: function(request, response) {
          var term = request.term;
          if (term in cache) {
              response(cache[term]);
              return;
          }

          lastXhr = $.getJSON("/products/get_json_list", request, function(data, status, xhr) {
              cache[term] = data;
              if (xhr === lastXhr) {
                  response(data);
              }
          });
      }
  });

我就像一个拿着这些东西的脚本小子。由于以下原因,我永远无法自己编写该匿名函数:

1)这个人如何知道将参数“请求”和“响应”放入规范中?

2)以“lastXhr =”开头的行确实很神秘。最后还有另一个匿名函数。我意识到这可能是一个回调,是在请求发送到指定 URL 后执行的。

3)匿名函数中的最后一个条件:

if ( xhr === lastXhr ) {                                                                                      
    response( data );
}

那到底是什么?如果此匿名块中的第三个参数 xhr 等于 .getJSON 调用返回的值包含此匿名块,则返回响应中的数据?

这确实是我最难理解的部分。我注意到这是 3 个等号。这看起来像是非常先进的代码概念,我只是想了解这背后的基本原理,以便我可以成为一名更好的编码员。

I know that it works. I have implemented it successfully.

$("#vehicle_application_product_id").autocomplete({
      minLength: 2,
      source: function(request, response) {
          var term = request.term;
          if (term in cache) {
              response(cache[term]);
              return;
          }

          lastXhr = $.getJSON("/products/get_json_list", request, function(data, status, xhr) {
              cache[term] = data;
              if (xhr === lastXhr) {
                  response(data);
              }
          });
      }
  });

I am like a script kiddie with some of this stuff. I would NEVER be able to write that anonymous function myself, because of the following reasons:

1) How did this person know to put the parameters "request" and "response" in the spec?

2) The lines beginning "lastXhr = " is really mystifying. There is yet another anonymous function at the end. I realize that is probably a callback, something that is executed after the request is sent to the specified URL.

3) That last conditional in the anonymous function:

if ( xhr === lastXhr ) {                                                                                      
    response( data );
}

What the heck is that? If then third parameter, xhr, from this anonymous block is equal to the vaue returned by the .getJSON call ENCOMPASSING this anonymous block, return the data in the response?

That is really the most difficult part to wrap my head around. And I notice that's 3 equals signs. This looks like pretty advanced code concepts, I would just appreciate what the rationale behind this is so that I can become a better coder.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冰魂雪魄 2024-12-15 20:51:07
  1. 参数requestresponse将被传递给分配给source选项的函数记录在此处。本质上,插件承诺将这两个参数传递给回调,这就是您表明您确实想要获取它们的方式。

  2. 该函数是一个回调函数,计划在请求完成时调用,而不是在请求发送后调用。此外,在调用 getJSON 时,代码会将结果对象分配给lastXhr 变量,以便它记住它发出的最后一个请求。

  3. 在回调中,您可以以参数xhr 的形式引用已完成的请求。因此 if 相当于编写:

    if(完成的请求是最后发出的请求){
        // ...
    }
    

    为什么要这样做?为了确保如果由于响应返回时间过长且用户输入速度过快而导致您有多个未完成的请求,您不会对请求的结果采取行动。在这种情况下,除了最后一个结果之外,您实际上对任何结果都不感兴趣。

    回调如何从外部作用域访问变量lastXhr?这是由于关闭

  4. 三个等号是怎么回事?这就是身份运算符

  1. The parameters request and response will be passed to the function assigned to the source option as documented here. In essence, the plugin promises to pass these two parameters to the callback and that's how you signal that you do want to get hold of them.

  2. That function is a callback scheduled to be invoked when the request completes, not after it's simply sent. Also, when calling getJSON, the code assigns the resulting object to the lastXhr variable so that it remembers which was the last request that it made.

  3. Inside the callback, you have a reference to the request that completed in the form of the parameter xhr. So that if is equivalent to writing:

    if (the request that completed is the last request made) {
        // ...
    }
    

    Why do this? To make sure that you do not act on the results of the request if, due to the response taking too long to come back and the user typing too fast, you have multiple outstanding requests. In such a scenario, you are really not interested in the results of any but the last one you made.

    How does the callback have access to the variable lastXhr from an outer scope? This is due to closure.

  4. What's with the three equal signs? That's the identity operator.

柠栀 2024-12-15 20:51:07

1) 他们在这里阅读了 jQuery UI 自动完成插件的文档:
http://jqueryui.com/demos/autocomplete/#option-source

2) lastXhr 的用法与 getJSON 的 jQuery 文档页面中显示的用法类似:http://api.jquery.com/jQuery.getJSON/

3) 编写代码的人可能希望 jQuery 自动完成功能仅显示最近 $.getJSON 的结果() 请求自动完成数据。例如,假设我输入“abc”并触发自动完成功能,但随后我输入“d”,所以现在它是“abcd” - 然后另一个自动完成功能触发。我们只关心“abcd”的结果,对吧?因此,检查 lastXhr 是否与当前 xhr 匹配即可!

请注意,JavaScript 中的 === 正在测试对象是否具有相同类型且相等。在 JS 中,1 == '1' 为 true,但 1 === '1' 则不然。我强烈推荐“JavaScript:优秀部分”,其中介绍了闭包的概念以及该语言的其他有趣方面。

1) They read the documentation for the jQuery UI Autocomplete plugin here:
http://jqueryui.com/demos/autocomplete/#option-source

2) The usage seen with lastXhr is similar to those shown the jQuery documentation page for getJSON: http://api.jquery.com/jQuery.getJSON/

3) The person writing the code likely wanted jQuery autocomplete to only show the results of the most recent $.getJSON() request for autocomplete data. For example, say I type "abc" and autocomplete fires but then I type "d" so it's "abcd" now -- then another autocomplete fires. We only care about the results for "abcd", right? So this check that lastXhr matches the current xhr does that!

Note that === in JavaScript is testing that the objects are of the same type and are equal. In JS, 1 == '1' is true but 1 === '1' is not. I highly recommend "JavaScript: The Good Parts" which goes into the concepts of closure and other interesting facets of the language.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文