相关疑难解决方法(0)

为什么要使用发布/订阅模式(在JS/jQuery中)?

所以,一位同事向我介绍了发布/订阅模式(在JS/jQuery中),但是我很难掌握为什么会使用这种模式而不是'普通'的JavaScript/jQuery.

例如,之前我有以下代码......

$container.on('click', '.remove_order', function(event) {
    event.preventDefault();
    var orders = $(this).parents('form:first').find('div.order');
    if (orders.length > 2) {
        orders.last().remove();
    }
});
Run Code Online (Sandbox Code Playgroud)

我可以看到这样做的优点,例如......

removeOrder = function(orders) {
    if (orders.length > 2) {
        orders.last().remove();
    }
}

$container.on('click', '.remove_order', function(event) {
    event.preventDefault();
    removeOrder($(this).parents('form:first').find('div.order'));
});
Run Code Online (Sandbox Code Playgroud)

因为它引入了removeOrder为不同事件等重用功能的能力.

但是,为什么你决定实现发布/订阅模式并转到以下长度,如果它做同样的事情?(仅供参考,我使用jQuery tiny pub/sub)

removeOrder = function(e, orders) {
    if (orders.length > 2) {
        orders.last().remove();
    }
}

$.subscribe('iquery/action/remove-order', removeOrder);

$container.on('click', '.remove_order', function(event) {
    event.preventDefault();
    $.publish('iquery/action/remove-order', $(this).parents('form:first').find('div.order'));
});
Run Code Online (Sandbox Code Playgroud)

我肯定已经读过关于这种模式的内容,但我无法想象为什么这种模式是必要的.我看过的解释如何实现这种模式的教程只是作为我自己的基本示例.

我认为pub/sub的有用性会在更复杂的应用程序中显现出来,但我无法想象.我担心我完全忽略了这一点; 但是如果有的话,我想知道这一点!

你能简洁地解释为什么以及在什么情况下这种模式是有利的?是否值得像上面的例子那样使用pub/sub模式进行代码片段?

javascript jquery design-patterns publish-subscribe

99
推荐指数
3
解决办法
7万
查看次数