Using "services"

28 views
Skip to first unread message

Boaz Hachlili

unread,
Dec 17, 2013, 7:16:09 AM12/17/13
to som...@googlegroups.com
Hi,
I'm writing my first project with somajs. It's a POC for a larger project where we're considering using somajs for the client-side architecture.
I understand the separation of concerns into view, model and mediator. But I'm not sure how to create services. 
For example, our app would need to manage localStorage to save user-specific data on the browser. 
Another example would be a statistics service which will subscribe to certain events, receive event data and send it to a server used for statistics and monitoring.
What is the correct component to use for these services? A mediator doesn't seem right in this case, and I'm pretty sure models or views aren't right either.

Thanks for your help,

Boaz

Romuald Quantin

unread,
Dec 17, 2013, 7:50:09 AM12/17/13
to
Hi there,

Models are good to manage data or applications states, so I'd say that your localStorage part could be a Model and as simple as that one:

var LocalStorageModel = function() {
    var storeKey = 'todos-somajs';
   return {
       get: function() {
           return JSON.parse( localStorage.getItem( storeKey) || '[]' );
       },
       set: function( items ) {
           localStorage.setItem( storeKey, JSON.stringify( items ) );
       }
   };
};

Then map it as a Singleton (only one instance with third parameter).

this.injector.mapClass('localStorage', LocalStorageModel, true);

To inject it with a constructor:

function something(localStorage) {

Or to inject it with a property

function something() {
   
this.localStorage = null;

For the service, as you can see the model is just a javascript function, nothing more. So you could create something like:

var StatisticsService = function() {
    var url = '/api/event';
   
this.sendEvent = function(data) {
       
// do some ajax
   
};
};

Again, it is only a function, you can build your own structure, one that makes to your app.

You can find an example there:

You can map the service that way (no need for a singleton):

this.injector.mapClass('statisticsService', StatisticsService);

And inject it the same way as the previous example with the model above.

I would abstract it even further by creating a command for an easy use:

this.commands.add('stats-send-event', StatisticsCommand);

var StatisticsCommand = function (statisticsService) {
   this.execute = function (event) {
       statisticsService.sendEvent(event.params);
   };
};

And to use:

function something(dispatcher) {
    dispatcher
.dispatch('stats-send-event', {data:'data'});
}

You can find an example of a command there:

Hope that helps!

romu


Boaz Hachlili

unread,
Dec 17, 2013, 7:50:24 AM12/17/13
to som...@googlegroups.com
Thanks for the fast reply. I'll give that a try.
Boaz
Reply all
Reply to author
Forward
0 new messages