なんかできたよー。

Web系Tipsを適当につづるBlog.

なぜか楽天商品検索API用コードをCoffeeScriptで書き直した

 


サンプルコードはこちら。

ヒアドキュメントのおかげでHTMLが直感的にわかりやすい。

class ItemSearch
  constructor: (@elem, initOpts)->
    # Default Options
    defOpts =
      sort: '%2DreviewCount'
    @options = $.extend(defOpts, initOpts)

  selectId: ->
    # Application ID List
    appId = [
      '4157e4f27453c452f3d6c7aa17365633'
    ]
    appId[Math.floor(Math.random() * appId.length)]

  generateURL: ->
    url = 'https://app.rakuten.co.jp/services/api/IchibaItem/Search/20120723?format=json&callback=?'
    url += '&applicationId=' + @selectId()
    for own key, val of @options
      if val is ''
        continue
      else if key is 'keyword' or key is 'NGKeyword'
        url += "&#{key}=#{encodeURIComponent(val)}"
      else
        url += "&#{key}=#{val}"
    return url

  getItems: ->
    url = @generateURL()
    $.getJSON url, (json)=>
      items = json.Items
      html = ''
      for item in items
        item = item.Item
        html += @viewHTML(item)
      $("\##{@elem}").html(html)

  viewHTML: (item)->
    #Please define later

  setOptions: (addOpts)->
    @options = $.extend(@options, addOpts)


# Create Instance

recommend = new ItemSearch(
  'recommend',
  keyword: 'coffee'
)


# Create View of Instance

recommend.viewHTML = (item)->
  html = """
  <p>
    <a href="#{item.itemUrl}">
      <img src="#{item.mediumImageUrls[0].imageUrl}">
      #{item.shopName} (#{item.reviewCount})
    </a>
  </p>
  """


# Get Item Data

recommend.getItems()


# Options Change

recommend.setOptions(keyword: 'script')