是否有一个JavaScript preprocessor,使得回调好看吗? [英] Is there a JavaScript preprocessor that makes callbacks look nice?

查看:128
本文介绍了是否有一个JavaScript preprocessor,使得回调好看吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript工具包像jQuery是所有有关回调函数,这些回调经常匿名定义。例如:一些网页示出了一个表的消息的列表。要更新此表时,它可能会先问服务器目前所有的消息的列表(标识),然后检索为尚未未知的消息ID的内容:

JavaScript toolkits like jQuery are all about callback functions, and those callbacks are frequently defined anonymously. Example: Some webpage shows a list of messages in a table. To update this table, it might first ask the server for a list of all current messages (as IDs), then retrieve the content for the yet-unknown message IDs:

function fnUpdateMessages() {
   $.ajax({
      type: 'POST',
      data: { action: 'get_message_ids' },
      success: function(sData) {
         var aMessageIds = sData.split(/,/);
         var aUnknownIds = fnWhichIdsAreNotInTable(aMessageIds);
         $.ajax({
            type: 'POST',
            data: {
               action: 'get_message_contents',
               ids: aUnknownIds.join(',')
            },
            success: function(oData) {
               for (var id in oData.messages) {
                  fnInsertMessage(oData.messages[id]);
               }
            }
         );
      }
   );
}

您看到我要去哪里?这code是丑陋的,因为压痕后只有2个后续Ajax调用处第6级。我当然可以在文件范围内分裂匿名函数为单独的功能,但通常污染了命名空间(除非杂波在另一个匿名函数调用包装这个进一步的东西),它打破了这些功能之间的牢固纽带:该回调应真的不自己使用;他们就像当初 fnUpdateMessages 函数的第二部分和第三部分。

You see where I'm going? This code is ugly, since indentation is at level 6 after only 2 subsequent AJAX calls. I can of course split the anonymous functions into separate functions at the file scope, but that usually pollutes the namespace (unless one clutters stuff further by wrapping this in another anonymous function call) and it breaks the strong bond between these functions: The callbacks should really not be used by themselves; they're just like the second and third part of the original fnUpdateMessages function.

我宁愿要的就是这样的:

What I'd much rather want is something like this:

function fnUpdateMessages() {
   $.ajax({
      type: 'POST',
      data: { action: 'get_message_ids' },
      success: continue(sData)
   });

   var aMessageIds = sData.split(/,/);
   var aUnknownIds = fnWhichIdsAreNotInTable(aMessageIds);
   $.ajax({
      type: 'POST',
      data: {
         action: 'get_message_contents',
         ids: aUnknownIds.join(',')
      },
      success: continue(oData)
   );

   for (var id in oData.messages) {
      fnInsertMessage(oData.messages[id]);
   }
}

这个片段引入了新的假设语法继续(VAR1,VAR2,[...])定义一个匿名的回调函数体是封闭函数后面的一切范围。这使得那些回调函数出现像同步code。这必须是preprocessed,很明显,因为它不是标准的JS。

This snippet introduces new hypothetical syntax continue(var1, var2, [...]) which defines an anonymous callback function whose body is everything that follows in the enclosing function scope. This makes those callback functions appear like synchronous code. That would have to be preprocessed, obviously, since it's not standard JS.

在我甚至考虑写这样的preprocessor,我想知道,如果这样的事情已经存在?

Before I even consider writing such a preprocessor, I would like to know if something like this already exists?

P.S。如果你喜欢这个想法,请偷。此刻我不能完全负担得起的又一项目。在评论到存储库的链接将是巨大的,你应该得到一些工作code。

P.S. If you like this idea, please steal it. I can't quite afford yet another project at the moment. A link to your repository in a comment would be great, should you get to some working code.

推荐答案

有只有两种解决方法:

首先是非常糟糕:你必须做出的第一个Ajax请求同步,但你的脚本将阻塞,直到结果可用。
这确实是一个坏的解决方案,你不应该做任何Ajax请求是同步的。

The first is really bad : you have to make the first ajax request synchronous but your script will block until result is available. This is really a bad solution, you should not make any ajax requests synchronous.

第二个使用由$就推迟对象回报jQuery.pipe功能(你必须使用jQuery> 1.5)。
您可以使用管道这样的链条回调(我用的内部函数,使其更具可读性):

The second one use the jQuery.pipe function on deferred object return by $.ajax (you have to use jquery > 1.5). You can chain callbacks using pipe like this (I use internal function to make it more readable) :

:因为jQuery的1.8,你应该使用的deferred.then代替deferred.pipe:

: since jquery 1.8, you should use deferred.then instead of deferred.pipe :

    function fnUpdateMessages() {
        var getMessages = function() {
            return $.ajax({
                type: 'POST',
                data: { action: 'get_message_ids' },
            });
        };

        var getContents = function(aUnknownIds) {
            return $.ajax({
                type: 'POST',
                data: {
                    action: 'get_message_contents',
                    ids: aUnknownIds.join(',')
                },
            });
        };

        var insertMessages = function(oData) {
            for (var id in oData.messages) {
                fnInsertMessage(oData.messages[id]);
            }
        };

        getMessages()
            .then(getContents)
            .done(insertMessages);
     }

这篇关于是否有一个JavaScript preprocessor,使得回调好看吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆