I'm writing a bit of code to encapsulate an angular animation into a coffeescript class. I think it's ugly. any suggestion to make it shine?
I don't like the fact that I have to create the object first and return an object with addClass and removeClass pointing it indirectly to my instance methods.
html used
<div ng-hide="..." class="message">...</div>
the ugly code
class MessageAnimation
constructor: () ->
console.log 'MessageAnimation:init'
animation_up: (element, cl, done) ->
element.removeClass cl
element.velocity 'slideUp',
duration: 500
complete: () ->
element.addClass cl
done()
return
animation_down: (element, cl, done) ->
element.velocity 'slideDown',
duration: 500
complete: () ->
done()
return
angular.module('some_nice_app').animation '.message', () ->
@messageAnimation = new MessageAnimation()
return {
addClass: @messageAnimation.animation_up
removeClass: @messageAnimation.animation_down
}
....but maybe I don't need a class after all, because it's only instantiated ones. what do you think?
you probably do not need to create a class unless you need to create state you need to reference from other methods. AKA, In the example you've given there is no, this.
reference in your methods. You can use classes as a convenient way to namespace methods, but in that case they are no different than a normal JS object. example:
class MessageAnimation
# the prefix of @ places this method on the prototype as a 'static' method
@animation_up: ->
angular.module('some_nice_app').animation '.message', () ->
addClass: MessageAnimation.animation_up # note: CS will automatically return the object, your use of return is redundant but some people prefer to be explicit.