Below is a simple implementation of pubsub as an angular service. I have
done this as a way to evaluate using Typescript to develop Angular modules.
The idea here is to have a class (Pubsub) that contains all of the logic
of this service, and can be newed up in unit tests. This allows test of
each of the methods within the class. This then permits an interface to be
created.
Then when integrating with Angular, the register function is called, which
creates a new instance of Pubsub (stored in a static var) and passes the
relevant methods onto Angular for use in the application. Some issues:
The interface passes to angular is not the same as the one I want to expose
to unit tests, so two interfaces? sounds a bit wrong to create an
interface for this purpose.
The class Pubsub now has a static instance property which is an
instatiation of itself, again sounds a bit wrong.
Any thoughts or opposing ideas on how to use Typescript with Angular are
greatly appreciated.
module SP.Services {
export interface IPubSub {
ensure(channelName: string);
publish(channelName: string, data: any);
subscribe(channelName: string, callback: any);
channels: {}[];
}
export class Pubsub implements IPubSub {
public channels: {}[];
static instance: IPubSub;
static providerName = 'PubSub';
/**
* register this object with angular
*/
static register(app: ng.IModule) {
var _pubsub = new Pubsub();
app.factory(Pubsub.providerName, () => {
return {
publish: _pubsub.publish,
subscribe: _pubsub.subscribe
};
});
}
/**
* ensure the channel exists
*/
public ensure(channelName: string) {
Pubsub.instance.channels[channelName] =
Pubsub.instance.channels[channelName] || [];
}
/**
* Publish data to a channel
*/
public publish(channelName: string, data: any) {
var _topic: any,
_i: number;
Pubsub.instance.ensure(channelName);
_topic = Pubsub.instance.channels[channelName];
for (_i = 0; _i < _topic.length; _i++) {
_topic[_i](data);
}
}
/**
* Subscribe to a channel
*/
public subscribe(channelName: string, callback: any) {
Pubsub.instance.ensure(channelName);
Pubsub.instance.channels[channelName].push(callback);
}
constructor() {
Pubsub.instance = this;
Pubsub.instance.channels = [];
}
}
}
--
You received this message because you are subscribed to the Google Groups
"AngularJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/angular.
For more options, visit https://groups.google.com/groups/opt_out.