I'm Benjamin Hollis, a software developer in Seattle. I build products that developers love.

More Projects

Cleanly declaring AngularJS services with CoffeeScript

| , , ,
I’ve recently fallen in love with AngularJS for building JavaScript applications. I’ve also come to rely on CoffeeScript to provide a more comfortable, concise syntax than plain JavaScript. It’s common to define many services when writing AngularJS applications. Services are just plain JavaScript objects that are registered with AngularJS' dependency injection system, which makes them available to other parts of your application. If you have experience with Java, this will be familiar from Spring or Guice. I prefer to have very little logic in my controllers, and instead create a domain model from layers of services that each have their own responsibility. One thing I’ve gone back and forth on is how best to declare AngularJS services using CoffeeScript. Let’s imagine a somewhat contrived example service named Tweets that depends on the built-in $http service. When it’s constructed it saves a timestamp, makes an HTTP call and saves the result to a property. Here’s a pretty straightforward way to declare this service using CoffeeScript’s class syntax: app.service 'Tweets', ['$http', class Tweets constructor: (@$http) -> @timestamp = Date.now() - 900000 @getNewTweets() getNewTweets: -> request = @$http.get '/tweets', params: { ts: @timestamp } request.then (result) => @tweets = result.data @timestamp = Date.now() ] This works pretty well. The first time this service is needed in the application, AngularJS will call new Tweets() and save that one (and only one) instance to be provided to any other code that requests it. Because AngularJS calls the Tweets constructor, the first call to getNewTweets is... more

Redesigning evafunderburgh.com

|
My wife Eva Funderburgh (Hollis) is a professional artist, and has been making sculptures full-time since we both moved to Seattle in 2005. I don’t... more