There are three things that are critical to Ajax-driven single-page applications: Time delegation, history management, and Communication mode (PUB/SUB).
First of all, let's introduce what pub/sub is. We can call this thing a broadcast, which means that when you publish something, everyone else gets it. You can think about it, generally in a single page application, is highly modular. Then there will be a communication problem, and in the past, we will declare a particular object, which is specifically used as a communication between modules. After using the pub/sub, the communication between the modules will be direct communication, so that the structure can become clear.
PS: This mechanism is integrated in angularjs, and the function of Angularjs is more complete.
The following code can be directly integrated into your own project, or can be slightly modified:
var events = (function () { var topics = {}; return { // receive subscribe: function (Topic, listener) { // first obtains the mark from the place to receive, generates the queue if in the topics ( !topics[topic]) topics[topic] = { queue: [] }; // put the listener in the queue var index = topics[topic ].queue.push (Listener) -1; // provides a function for removal return { remove: function () { delete topics[topic].queue[index]; } }; }, // Push publish: function ( Topic, info) { // If there is no place to receive it, then you don't have to push if (!topics[topic] | | !topics[topic].queue.length) return; // execute the receive function, if there is no information to be passed, Then send an empty object var items = topics[topic].queue; items.foreach (function (item) { item (info | | {}); }); } };}) ();
When you want to push a message:
Events.publish ('/page/load ', {url: '/some/url/path '//Information sent});
The first parameter is an indication, or it can be said to be a subscription number.
The way to receive it is this:
var subscription = Events.subscribe ('/page/load ', function (obj) {//process the obtained information});//You can also use Remove to cancel receiving subscription.remove ( );
Listen to the data according to the mark
Via:http://davidwalsh.name/pubsub-javascript