Quantcast
Viewing all articles
Browse latest Browse all 16

Answer by Sky Sanders for OBSOLETE - Soapi.JS : fluent JavaScript client library for the Stack Exchange API

Enumerated Constants, or enums, in Soapi.js

The advantages of using enums include the elimination of magic strings scattered about your codebase and the ability to update all references to an enum value in one location.

Typically, in a statically typed language, enums are readonly or immutable values. While this concept is alien to the dynamically typed JavaScript language the benefits of enums are not mitigated. You simply need to treat them as immutable and not assign values to them.

Soapi.js defines 'enums' for all of the 'choice' parameters and return types in the API. Using enums may seem like more work in that they are more verbose than using string constant but in reality they make your code more robust and much easier to read and maintain.

For example:

var $sd = Soapi.Domain;// as a parameterroute.Sort = $sd.UserSort.reputation;// identifying values in return typesswitch(user.user_type){   case $sd.UserType.anonymous:      // do something       break;   case $sd.UserType.unregistered:      // do something       break;   case $sd.UserType.registered:      // do something       break;   case $sd.UserType.moderator:      // do something       break;}

Enums used in parameters

SortOrder

  • desc
  • asc

PostSort

  • activity
  • views
  • creation
  • votes

CommentSort

  • creation
  • votes

QuestionSort

  • activity
  • votes
  • creation
  • featured
  • hot
  • week
  • month

TagSort

  • popular
  • activity
  • name

UserSort

  • reputation
  • creation
  • name

FavoritesSort

  • activity
  • views
  • creation
  • added
  • votes

Enums used in return types

SiteState

  • normal
  • closed_beta
  • open_beta
  • linked_meta

UserType

  • anonymous
  • unregistered
  • registered
  • moderator

PostType

  • question
  • answer

PostTimelineType

  • question
  • answer
  • comment
  • revision
  • votes
  • state
  • accepted
  • unaccepted

RevisionType

  • single_user
  • vote_based

UserTimelineType

  • comment
  • askoranswered
  • badge
  • revision
  • accepted

Users of Visual Studio will get extra benefit from the use of the defined enum types as they have the luxury of intellisense code completion, which will be covered in detail in the Intellisense Support post.

Image may be NSFW.
Clik here to view.
alt text

Next: Studio JavaScript Intellisense and Code Completion Support


Viewing all articles
Browse latest Browse all 16

Trending Articles