0

代码示例:

var Events = $({});

Events.on('myCustomEvent', function(){ console.log('myCustomEvent 1') })

Events.trigger('myCustomEvent'); // I want notify the previous binds and all binds in future

$.ajax({...}).success(function(res){
    Events.on('myCustomEvent', function(){ console.log('myCustomEvent 2') })
});

// when ajax or other long process will be finished 'myCustomEvent' must be fired

'myCustomEvent 1' 将被打印,因为它在触发器之前绑定将被调用并且 'myCustomEvent 2' 也必须被触发

jQuery中有什么解决方案吗?

4

2 回答 2

0

我认为解决方案是 $.Callbacks

Callbacks.highlight = $.Callbacks('memory')

// ComponentB
$(window).hashchange(function(){

    $.ajax({ /* load items of #ListB */ }).success(function(data){

        /* append items to dom */

        if (/listA=123/.test(location.hash))
            Callbacks.highlight.fire();
    })

    $('#ListB').on('click', 'a', function(){ /* highlight the same in #ListA by alg2 */ })
})

// ComponentA
$(window).hashchange(function(){

    $.ajax({ /* load items of #ListA */ }).success(function(data){

        /* append items to dom */
        Callbacks.highlight.add( /* highlight item */ )
    })

    $('#ListA').on('click', 'a', function(){ /* highlight the same in #ListB by alg1 */ })
})
于 2012-05-26T16:46:14.223 回答
0

看起来你想要的不是很多事件,而是一个发布/订阅系统,或者实现观察者模式的代码。这些实现中的大多数都没有能力在消息发布后追溯呼叫订阅者。我已经做到了,但是您需要小心,使用该系统的任何人都知道一条消息可能会被多次发布。不幸的是,我无法分享代码,因为它归我的雇主所有。

只需搜索“JavaScript 中的观察者模式”或“JavaScript 中的 pubsub”即可获得一个很好的库。通常,这些使用“主题”的散列到发布该主题时调用的函数数组。诀窍是还保留调用发布时间的历史记录。当有人订阅已经发布的主题时,重新发布该主题。

希望这足以让你开始。

于 2012-05-24T20:50:47.427 回答