0

Suppose I want to implement a simple EventBus pattern in javascript using jQuery. The page has a div where I load some dynamic content using $().load(). This content has some javascript code which subscribes to some events on $(document).ready()

page1.html:

$(document).ready(function() {
    $eventBus.on("next", function() {
        // do something
    });        
});

root.html

$("#content").load("page1.html"); // load page1 and invoke it's javascript

How should I properly unsubscribe this event handler when another content with other script is loaded in the same div? I.e. where is the best place to put $eventBus.off("next");

What I am really want to achieve is to make inner pages subscribe to some events on load and unsubscribe on unload

ike3
  • 1,760
  • 1
  • 17
  • 26

1 Answers1

0

So first, it seems like you are looking to design your own SPA framework. Why? There are many out there. Use angular, or ember, or knockout, or react, or flight.

Next, if you're going to create your own framework you're going to have to create your own framework, don't to half-ass it. That means you need an api that wraps a lot of jquery stuff so that you have the necessary hooks.

Off the top of my head you can do something like this

MyFramework.load({url: 'page1.html', target: '#content'}).then(...)

Then MyFramework.load would so something like

MyFramework.load = (op) => {
    return $.Deferred( (d) => {
        $.get(op.url).then((html)=>{
            if(currentContexts[op.target])
                MyFramework.unload(currentContexts[op.target])
            var ctx = $.extend({}, op);
            ctx.subscriptions = MyFramework.events.trackSubscriptions(() => {
                 $(op.target).html(html);
            });
            d.resolve();
        });
    });
}

All event subscriptions will either have to go through your own API or you will have to override jquery.on so that you can track them.

The above is not perfect and you'd still have to implement unload, trackSubscriptions, your own message subscribing API, and some way to track events that were not subscribed to immediately, but this basic idea would work.

Again though, I'll caution. It's hard. If you don't understand all the above code you shouldn't even attempt it (and maybe you shouldn't even if you do). Just use an existing framework.

George Mauer
  • 117,483
  • 131
  • 382
  • 612