multithreading And Subscribe/Publish approach in javascript - javascript

I understand that there is no multithreading support in javascript. And i wanted some expert advice on the below scenario..
My requirement is to perform a AJAX call and upon successful completetion, i want to trigger set of events (to update the different parts of UI parallely)
I am planned to use Subscribe/Publish pattern, is it possible to subscribe multiple listners to the AJAX completion event.
If possible, i wanted to know how these listners notified on publish.. (parallely in muthithreaded way or one by one).
And suggest me the best way to achive this one.. I really appreciate your thoughts.
EDIT::
I know there are popular frameworks like JQuery supports this pattern. But am in a situation to develop this functionality from a scratch (we have our own framework).

I've a Request Pooler that might give you a good head-start here. [Since this answer was accepted I've retired the pooler in favor of a more complete "AJAX Helper" - the link has been updated.]
I'm not sure that'll do everything you want (although it sounds like it may be close). It's old, but it works:
Depressed Press DP_AJAX
It supports multiple simultaneous requests with timeout/retry, per-request handlers, has a very small footprint and can be combined with other code easily.
You create a pool (telling it how many simultaneous requests are allowed) and then toss requests at it. When they're done they call whatever handler you specified.
A small, complete example of it's use:
// The handler function
function AddUp(Num1, Num2, Num3) {
alert(Num1 + Num2 + Num3);
};
// Instantiate the Pool
myRequestPool = new DP_RequestPool(4);
// Start the Interval
myRequestPool.startInterval(100);
// Create the Request
myRequest = new DP_Request(
"GET",
"http://www.mysite.com/Add.htm",
{"FirstNum" : 5, "SecondNum" : 10},
AddUp,
[7,13]);
// Add the request to the queue
myRequestPool.addRequest(myRequest);
It's open source - feel free to chop/fold/spindle or mutilate it to your hearts content.
Jim Davis

This article describes what you're trying to accomplish pretty closely. Essentially you just have a JavaScript file that holds an array of handlers/subscribers. Each subscriber registers itself with the publisher (i.e. gets added to the handlers array). Then in the onClose handler of your Ajax call, you'd call a function that iterates over the subscribers and notifies them each by name:
this.handlers = [];
...
for(var i = 0; i < this.handlers.length; i++)
{
this.handlers[i].eventHandler.call(this, eventArgs);
}
...

Could this serve as a ligthweight message passing framework?
function MyConstructor() {
this.MessageQueues = {};
this.PostMessage = function (Subject) {
var Queue = this.MessageQueues[Subject];
if (Queue) return function() {
var i = Queue.length - 1;
do Queue[i]();
while (i--);
}
}
this.Listen = function (Subject, Listener) {
var Queue = this.MessageQueues[Subject] || [];
(this.MessageQueues[Subject] = Queue).push(Listener);
}
}
then you could do:
var myInstance = new MyConstructor();
myInstance.Listen("some message", callback());
myInstance.Listen("some other message", anotherCallback());
myInstance.Listen("some message", yesAnotherCallback());
and later:
myInstance.PostMessage("some message");
would dispatch the queues

This is possible and you should really use a library for that to avoid all the browser incompatibilities. For example jQuery provides Ajax functionality that lets you execute code on completion of the Ajax call. See here for documentation.

if you want to fire functions in parralell use following:
this.handlers = [];
...
for(var i = 0; i < this.handlers.length; i++)
{
setTimeout(function(){this.handlers[i].eventHandler.call(this, eventArgs);},0);
}
...

Related

JavaScript same functions, different implementation decided on runtme

What is the best way to change JavaScript implementations at run time?
I have a web application which connects to the server by SignalR.
If there is any problem connecting to the server using SignalR at runtime, I want to change the services functions implementations to work with regular XHR.
I have one js file with the following functions to connect via SignalR:
function initializeConnection() {
// Initialize connection using SignalR
}
function sendEcho() {
// Sending echo message using signalR
}
And another js file with the same functions for connection via XHR:
function initializeConnection() {
// Initialize connection using XHR
}
function sendEcho() {
// Sending echo message using XHR
}
I know it is impossible to have them loaded at the same time.
I know I can use one file with a toggle within each function.
I thought maybe I can switch between these files by loading & unloading them at runtime. Is this possible? If so, is this the best way for such an issue?
What is the best way for supplying different implementations at runtime?
One way to do it, is to define both implementations as objects with same signatures and just set the namespace to a variable:
;var MyStuff = {
//SignalR
SignalR: {
initializeConnection: function(){console.log('SignalR.initializeConnection()')},
sendEcho: function(){console.log('SignalR.sendEcho()')}
},
//XHR
XHR: {
initializeConnection: function(){console.log('XHR.initializeConnection()')},
sendEcho: function(){console.log('XHR.sendEcho()')}
}
};
//Do whatever check you want to
var mNamespace = (1 === 2) ? MyStuff.SignalR : MyStuff.XHR;
//Call the instance
mNamespace.initializeConnection();
You can also keep them split in two files and add them both to MyStuff dynamicallly:
//File 1
;var MyStuff = (MyStuff === undefined) ? {} : MyStuff;
MyStuff.SignalR = {..};
//File 2
;var MyStuff = (MyStuff === undefined) ? {} : MyStuff;
MyStuff.XHR = {..};
One pattern that can help you is the "lazy function definition" or "self-defining function" pattern. It consists of (as its name points out) the redefinition of a function at runtime. It's useful when your function has to do some initial preparatory work and it needs to do it only once.
In your case, this "preparatory" work would be selecting the function that handles the client-server connection.
For instance:
var sendMessage = function() {
// Perform a check, or try a first message using your default connection flavour
// Depending on the result, redefine the function accordingly
sendMessage = sendMessageUsingWhatever;
};
//Use sendMessage anywhere you want, it'll use the proper protocol
This pattern was particularly handy when dealing with browsers and their peculiarities:
var addHandler = document.body.addEventListener ?
function(target, eventType, handler) {
target.addEventListener(eventType, handler, false);
} :
function(target, eventType, handler) {
target.attachEvent("on" + eventType, handler);
};
In this case, it is useful to determine which which way to attach event listeners depending on the availability (or not) of a particular method.
It has its drawbacks though. For instance, any properties you've previously added to the original function will be lost when it redefines itself.
Hope it helps or at least gives you some ideas.

Passing a non-standard Scheduler to an operator

Let's say that I want to pass a Scheduler to an RxJS operator that makes it emit notifications every 5 seconds. Of course, this is very easy to do by just using interval or other existing operators. But if I really want to use a scheduler to accomplish that, how would I go about it?
My first thought is to subclass Rx.Scheduler.default. Would that be the way to go? And if so, how could that subclass look? Again, I understand that this is a complicated way to accomplish something that's easy using operators, but I am just curious about custom schedulers.
Operations should always be independent of the Schedulers that are used to implement them. Schedulers only know about one thing, time. Every scheduler is specifically built to deal with its own notion of time. They are expressly not built to handle specific operators since that would be a conflation of concerns.
So for your stated goal of creating a recurring task, I wouldn't recommend trying to actually create your own scheduler, it simply isn't needed. Schedulers come with an interface that already supports this.
You can use either the schedulePeriodic or the scheduleRecursiveFuture to accomplish this.
//Using periodic
Rx.Observable.interval = function(period, scheduler) {
return Rx.Observable.create(function(observer) {
return scheduler.schedulePeriodic(0, period, function(count) {
observer.onNext(count);
return count + 1;
});
});
};
//Using scheduleRecursive
Rx.Observable.interval = function(period, scheduler) {
return Rx.Observable.create(function(observer) {
return scheduler.scheduleRecursiveFuture(0, period, function(count, self) {
observer.onNext(count);
self(period, count + 1);
});
});
};
Reference 1,
Reference 2;
The former should be easier to wrap your head around, essentially it is just scheduling something to occur repeatedly spaced in time based on the period parameter.
The latter is usually a little more difficult to explain, but essentially you are scheduling a task and then sometime during the execution of that task you are rescheduling it (which is what the self parameter) is doing. This allows you do get the same effect using the period parameter.
The timing of this work is all directly affected by which scheduler you decide to pass into the operator. For instance, if you pass in the default it will try to use the best method for an asynchronous completion, whether that be setTimeout, setInterval or some other thing I can't remember. If you pass in a TestScheduler or a HistoricalScheduler this actually won't do anything until you increment each of their respective clocks, but doing so gives fine grained control over how time flows.
tl;dr Only implement new Schedulers if you have some new overall notion of time to express, otherwise use the existing API to do work on whatever Scheduler best fits how you want time to pass.
Should you roll your own?
Plainly: No. Most likely you can get done what you need done with an existing operator. Something like buffer, window, sample, etc. Scheduler development is not completely straightforward.
How to roll your own RxJS 4 Scheduler
If you want to implement your own Scheduler, in RxJS 4, you'd subclass Rx.Scheduler, then override each schedule method: schedule, scheduleFuture, schedulePeriodic, scheduleRecursive, scheduleRecursiveFuture... You'd also likely want to override now to return something relevant to your schedule.
Here is an example of a custom scheduler that uses button clicks inside of real time
/**
NOTE: This is REALLY fast example. There is a lot that goes into implementing a
Scheduler in RxJS, for example what would `now()` do in the scheduler below? It's also missing a number of scheduling methods.
*/
class ButtonScheduler extends Rx.Scheduler {
/**
#param {string} the selector for the button (ex "#myButton")
*/
constructor(selector) {
super();
this.button = document.querySelector(selector);
}
schedule(state, action) {
const handler = (e) => {
action(state);
};
const button = this.button;
// next click the action will fire
button.addEventListener('click', handler);
return {
dispose() {
// ... unless you dispose of it
button.removeEventListener('click', handler);
}
};
}
// Observable.interval uses schedulePeriodic
schedulePeriodic(state, interval, action) {
const button = this.button;
let i = 0;
const handler = (e) => {
const count = i++;
if(count > 0 && count % interval === 0) {
state = action(state);
}
};
// next click the action will fire
button.addEventListener('click', handler);
return {
dispose() {
// ... unless you dispose of it
button.removeEventListener('click', handler);
}
};
}
}
Rx.Observable.interval(1, new ButtonScheduler('#go'))
.subscribe(x => {
const output = document.querySelector('#output');
output.innerText += x + '\n';
});
How to do it in RxJS 5 (alpha)
Scheduling changed again in RxJS 5, since that version was rewritten from the ground up.
In RxJS5, you can create any object that adheres to the following interface:
interface Scheduler {
now(): number
schedule(action: function, delay: number = 0, state?: any): Subscription
}
Where Subscription is just any object with an unsubscribe function (same as dispose, really)
Once again, though, I don't advise creating a scheduler unless it's completely necessary.
I really hope that helps answer your question.

Can I put a CollaborativeString inside a custom type?

I'm reading the Google Drive Realtime API documentation on Building a Collaborative Data Model.
I really like the way gapi.drive.realtime.databinding.bindString behaves. It doesn't mess up your cursor placement when multiple people are typing in the same text box. But it requires that you pass it a CollaborativeString.
But if you register a custom type, you have to use gapi.drive.realtime.custom.collaborativeField no matter what type of field you are defining, and you can't pass one of these to bindString. In fact, the collaborativeField type does not appear to be documented anywhere, and inspecting it in the console shows that it has no methods. That means there's no registerReference method, which CollaborativeString uses to keep track of cursor positions.
How frustrating. So I guess I have to work around it. I see a few options:
Ignore the fact that the cursor gets messed up during collaboration
Use a CollaborativeMap instead of a custom type, and wrap it with my custom type at runtime
Probably going to do option 2.
I think you misunderstand how this site works, the onus is not on other people to show you how to do something - you're asking other people to take time from their day and help you.
That being said, taking a quick look at the page that you linked shows that what you want to do is not only possible but quite straightforward and compatible with bindString. Stealing from the example code from that page:
// Call this function before calling gapi.drive.realtime.load
function registerCustomTypes()
{
var Book = function () { };
function initializeBook()
{
var model = gapi.drive.realtime.custom.getModel(this);
this.reviews = model.createList();
this.content = model.createString();
}
gapi.drive.realtime.custom.registerType(Book, 'Book');
Book.prototype.title = gapi.drive.realtime.custom.collaborativeField('title');
Book.prototype.author = gapi.drive.realtime.custom.collaborativeField('author');
Book.prototype.isbn = gapi.drive.realtime.custom.collaborativeField('isbn');
Book.prototype.isCheckedOut = gapi.drive.realtime.custom.collaborativeField('isCheckedOut');
Book.prototype.reviews = gapi.drive.realtime.custom.collaborativeField('reviews');
Book.prototype.content = gapi.drive.realtime.custom.collaborativeField('content');
gapi.drive.realtime.custom.setInitializer(Book, initializeBook);
}
and
// Pass this as the 2nd param to your gapi.drive.realtime.load call
function onDocLoaded(doc)
{
var docModel = doc.getModel();
var docRoot = docModel.getRoot();
setTimeout(function ()
{
var book = docModel.create('Book');
book.title = 'Moby Dick';
book.author = 'Melville, Herman';
book.isbn = '978-1470178192';
book.isCheckedOut = false;
book.content.setText("Call me Ishmael. Some years ago - never mind how long precisely - having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world.");
docRoot.set('tbook', book);
debugger;
}, 0);
}
Good luck and have fun with the Realtime API - it's a lot of fun to play with.
I know this question and answer are getting old, but for reference's sake, just the last part of Grant Watters' very good answer, the onDocLoaded routine, is rather misleading. That function as written, is more suited for the 3rd parameter to the gapi.drive.realtime.load call, the onInitializeModel callback.
The 2nd parameter is called every time the Doc is loaded. You wouldn't normally add the same object over and over as the above routine would... Instead, you would normally set up your event handling, your dataBinds etc. This version might clarify somewhat:
// Pass this as the 2nd param to your gapi.drive.realtime.load call
function onDocLoaded(doc)
{
var docModel = doc.getModel();
var docRoot = docModel.getRoot();
var text = doc.getModel().getRoot().get("text");
// Add an event listener...
text.addEventListener(gapi.drive.realtime.EventType.TEXT_INSERTED, onStringChanged);
// ...and/or bind to collaborative objects:
var textArea = document.getElementById('textArea1')
textBinding = gapi.drive.realtime.databinding.bindString(text, textArea);
etc...
}
Not incidentally, bindString returns the binding object, which is needed to "unbind" later, preventing an AlreadyBound error or other unexpected behavior when the next Doc is loaded. Do something like this:
function onDocLoaded(doc)
{
// Clear any previous bindings etc:
if (textBinding) { textBinding.unbind() };
textBinding = null;
etc...

Do I need Web Workers for looping AJAX-requests?

Given: a php-script for parsing portions of data on a web-site. It parses about 10k products hence rather slow.
I need to make a web-frontend with html/css/js for it. I made a loop which makes ajax-requests and shows progress inforamtion. It uses syncronous ajax because it needs to wait until another request is done to perform another.
do {
var parseProductsActive = true;
var counter = 0;
myAjax('parseProducts.php?start='+counter, false, function(resp) {
if (resp[0]=='s') {
counter += Number(resp.substring(1));
parseProductsActive = false;
}
else {
counter += Number(resp);
}
self.postMessage(counter);
});
} while (parseProductsActive==true);
I'm doing it in a Web Worker because I'm afraid it's going to hang up the interface because of this endless loop and (a)synchronousness of ajax itself won't help to solve the prolem.
But when I tried to use ajax in a web worker I found it's hard though possible because jQuery doesn't work in a Web Worker at all. It uses DOM even for non-DOM operations and DOM isn't available in a Web Worker. And many developers doubt using Web Workers at all. I just wanted to ask if I am doing it right or wrong. Is there any more surface solutions to that I can't see?
You guessed right: a recursive callback is the way to do a bunch of asynchronous requests in sequence. It might look a bit like this:
var parseProductsActive = true;
var counter = 0;
//define the loop
function doNextAjax(allDone){
//Instead of just returning, an async function needs to
//call the code that comes after it explicitly. Receiving a callback
//lets use not hardcode what comes after the loop.
if(!parseProductsActive){
allDone();
}else{
//use async Ajax:
myAjax('parseProducts.php?start='+counter, true, function(resp) {
if (resp[0]=='s') {
counter += Number(resp.substring(1));
parseProductsActive = false;
}
else {
counter += Number(resp);
}
self.postMessage(counter);
doNextAjax(); // <---
});
}
//Start the loop
doNextAjax(function(){
console.log("the code that runs after the loop goes here")
});
//BTW, you might be able to get rid of the "parseProductsActive" flag with a small
// refactoring but I'm keeping the code as similar as possible for now.
//It would be kind of equivalent to writing your original loop using a break statement.
Yes, its ugly and verbose but ints the only way to do it in raw Javascript. If you want to write a more structured version that looks like a loop instead of something with tons of gotos, have a look at one of the async control flow libraries or one of the compilers that compiles extensions of Javaascript with async support back into regular JS with callbacks.

How would you implement an 1. asynchronous event queue that 2. has event coalescing capabilities

Setting:
let's say three events happen in three separate part of some application, the event should be handled by two controllers. The application dispatcher is responsible for sending/receiving events from all parts of the application, and this dispatcher should have an asynchronous event queue.
In some cases, two the of three events are related along some attribute but are not of the same name, and only one should be passed to the controller, the other one may be discarded.
Problem:
Currently, I have a 'queue' that really just bounces the event to the controller, this is unhelpful because I have no way of comparing two events in the queue if only one is ever there at time.
So how do I ensure the events should stay in the queue for a while? I suppose a timeout function could do the trick but is there a better way?
To give credit where it's due, the idea of coalescing events is inspired by Cocoa and I'm basically trying to do something similar.
I don't know much about Cocoa, but I assume that it replaces older events with the latest event until the event is able to be dispatched to the application (i.e. if the application is busy for some reason). I'm not sure what your particular use case is, but if you want to rate-limit the events, I would use setTimeout like this:
function Dispatcher(controllers) {
this.controllers = controllers;
this.events = [];
this.nextController = 0;
}
Dispatcher.prototype = {
_dispatch: function (i) {
var ev = this.events.splice(i, 1);
this.controllers[this.nextController].handle(ev);
this.nextController = (this.nextController + 1) % this.controllers.length;
},
notify: function (ev) {
var index = -1, self = this, replace;
function similer(e, i) {
if (e.type === ev.type) {
index = i;
return true;
}
}
replace = this.events.some(similar);
if (replace) {
this.events[i] = ev;
} else {
// it's unique
index = this.events.push(ev) - 1;
setTimeout(function () {
self._dispatch(index);
}, 100);
}
}
};
Just call notify with the event (make sure there's a type property or similar) and it will handle the magic. Different types of events will be handled uniquely with their own setTimeout.
I haven't tested this code, so there are probably bugs.
I suppose a timeout function could do the trick but is there a better way?
No, there really isn't.
Usually the way to go is using setTimeout(..., 0) if your events are dispatched in the same run loop. So the implementation would look something like this:
var eventQueue = [];
var handlerTimer = -1;
function fireEvent(event, params) {
eventQueue.push([event, params]);
window.clearTimeout(handlerTimer);
handlerTimer = window.setTimeout(resolveQueue, 0);
}
function resolveQueue() {
// process eventQueue and remove unwanted events...
// then dispatch remaining events
eventQueue = [];
}
If you need to handle events from different run loops (for example native events like mouseup and click), you need to use some timeout value other than 0. The exact value depends on how long you want to accumulate events.

Categories

Resources