jQuery 中自定义回调的松散耦合

发布于 2024-12-14 06:06:17 字数 930 浏览 2 评论 0原文

我想知道是否存在一种设计模式/框架允许 jQuery 中回调的松散耦合。

基本上,我有一个 ajax 调用,它检索回调函数中所需的设置。我有许多希望在 ajax 调用完成后触发的函数,但希望避免执行以下操作:

$.getJSON('/webservice/config', function(data) {
    functionA();
    functionB();
}

我希望它是松散耦合的。有谁知道这是如何实现的吗?

谢谢, 齿轮。

解决方案

这是我最终使用的:

function initConfig(callbacks) {

    $.getJSON('/webservices/config', function(data) {       

        $.each(data.config, function(key, value) { 
          config[data.config[key].paramName] = data.config[key].paramValue; 
        });

    }).done(function() {
        //callbacks
        callbacks.forEach(function(callback) {
           if (eval('typeof ' + callback) == 'function') {
            window[callback]();
        });
    });
}

我的代码是相当松散耦合的,因为我可以将任意数量的回调函数传递给原始函数,并且它们将按顺序运行,例如:

initConfig('setLocationData', 'setUserData');

I was wondering if there exists a design pattern/framework which allows for the loose coupling of callbacks in jQuery.

Basically, I have a ajax call which retrieves settings that will be required in the callback functions. I have a number of functions that I wish to fire after the ajax call is complete but would like to avoid doing something like:

$.getJSON('/webservice/config', function(data) {
    functionA();
    functionB();
}

I'd like it to be loosely coupled. Does anyone have an idea on how this is popssible?

Thanks,
Gearoid.

SOLUTION

Here's what I used in the end:

function initConfig(callbacks) {

    $.getJSON('/webservices/config', function(data) {       

        $.each(data.config, function(key, value) { 
          config[data.config[key].paramName] = data.config[key].paramValue; 
        });

    }).done(function() {
        //callbacks
        callbacks.forEach(function(callback) {
           if (eval('typeof ' + callback) == 'function') {
            window[callback]();
        });
    });
}

My code is then quite loosely coupled as I can pass any number of callback functions to the original function and they will run sequentially, eg:

initConfig('setLocationData', 'setUserData');

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

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

发布评论

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

评论(3

粉红×色少女 2024-12-21 06:06:17

jqXHR 对象是所有 AJAX 查询的返回值,支持 < code>done 方法,允许您绑定在请求完成时执行的任意函数;

jQuery.getJSON('/foo.json').done(function () {
 // One success handler
}).done(function () {
 // Another success handler
});

这是因为 AJAX 模块在 jQuery 1.5 中被重写为使用 Deferred 接口,这保证回调触发之前或之后绑定的处理程序的执行。

编辑:解释我的评论

function initConfig() {
    return $.getJSON('/webservices/config', function(data) {       
        $.each(data.config, function(key, value) { 
          config[data.config[key].paramName] = data.config[key].paramValue; 
        });
    });
}

initConfig().done(setLocationData, setUserData);

The jqXHR object, which is the return value of all AJAX queries, supports a done method which allows you to bind arbitary functions which are executed on the completion of the request;

jQuery.getJSON('/foo.json').done(function () {
 // One success handler
}).done(function () {
 // Another success handler
});

This is because the AJAX module was rewritten in jQuery 1.5 to use the Deferred interface, which guarantees the execution of handlers which are bound either before or after the callback fires.

Edit: Explain my comment

function initConfig() {
    return $.getJSON('/webservices/config', function(data) {       
        $.each(data.config, function(key, value) { 
          config[data.config[key].paramName] = data.config[key].paramValue; 
        });
    });
}

initConfig().done(setLocationData, setUserData);
生生漫 2024-12-21 06:06:17

$.ajax 函数可以接受多个成功回调。引用自 http://api.jquery.com/jQuery.ajax/

从 jQuery 1.5 开始,成功设置可以接受函数数组。每个函数都会被依次调用。

简短示例:(参见 http://jsfiddle.net/JhTDW/

$.ajax({
  url: '/echo/json/',
  success: [
    function(data) {
      document.write('First callback: ' + data + '<br/>');
    },
    function(data) {
      document.write('Second callback: ' + data + '<br/>');
    }
  ]
});

The $.ajax function can accept multiple success callbacks. Quote from http://api.jquery.com/jQuery.ajax/:

As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn.

Short example: (see http://jsfiddle.net/JhTDW/)

$.ajax({
  url: '/echo/json/',
  success: [
    function(data) {
      document.write('First callback: ' + data + '<br/>');
    },
    function(data) {
      document.write('Second callback: ' + data + '<br/>');
    }
  ]
});
转身以后 2024-12-21 06:06:17

不确定它需要多么松散地耦合,但在成功回调中,您始终可以将 data 对象发送到另一个函数。但我不确定这将如何使事情脱钩。在一种情况下,您从成功回调中调用 functionA()functionB();在另一种情况下,您将数据发送到正在运行 functionA()functionB()utilityFunction()

在任何一种情况下,您都可以有一个或多个条件来运行 functionA() functionB() (或任何其他函数)。但同样,这可以在成功回调中或在实用函数中完成,所以我仍然不确定解耦将在哪里发生。

问题的核心是:您得到数据返回,并且大概您想要对该数据采取行动,或者至少根据响应运行逻辑。它会尽可能地解耦,从那里开始,这只是您想要如何构建它的问题。

Not sure how loosely it needs to be coupled, but in the success callback you could always send your data object to another function. But I'm not sure how this is going to decouple things. In one case, you're calling functionA() and functionB() from within the success callback; in the other case you're sending data over to utilityFunction() which is running functionA() and functionB().

In either case, you could have one or more conditionals in place to run functionA() or functionB() (or whatever other functions). But again, this could be done either in the success callback or in the utility function, so I'm still not sure where the decoupling will happen.

At the core of the question is this: You get data back, and presumably you want to act on that data or at least run logic depending on the response. It's about as decoupled as it's going to get, and from there it's just a matter of how you want to structure it.

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