Takazudo hamalog

programming notes. mainly about JavaScript / jQuery. [@Takazudo] [takazudo@gmail.com] Hint: alt + /

cool guy

SpineでMVCでTwitter検索なやつ

2012/02/17 permalink

Twitter検索してModelを更新してControllerがリフレッシュするようなやつ。シンプルに書ける風。

# Template manager
# //hamalog.tumblr.com/post/13593032409/jquery-tmpldeck
deck = $.TmplDeck 'templates.html'

# ============================================
# API wrapper
# ============================================

api =
  getTweets: (query) ->
    $.Deferred (defer) ->
      $.ajax
        url: 'http://search.twitter.com/search.json'
        dataType: 'jsonp'
        data:
          result_type: 'recent'
          rpp: 10
          page: 1
          q: query
      .pipe (res) ->
        defer.resolve res.results
      , ->
        alert 'error!'

# ============================================
# Models
# ============================================

class Tweet extends Spine.Model
  @configure 'Tweet', 'from_user', 'profile_image_url', 'text'
  @knock = (query) ->
    api.getTweets(query).done (tweets) =>
      @destroyAll()
      @refresh tweets, clear: true
      if not tweets.length then @trigger('noresults')

# ============================================
# Controllers
# ============================================

class TweetItemDiv extends Spine.Controller
  constructor: (@data) ->
    super
    @data.bind 'destroy', @remove
  render: =>
    @html( deck.tmpl 'item', @data.toJSON() )
    @
  remove: =>
    @el.remove()
    
class TweetsDiv extends Spine.Controller
  constructor: ->
    super
    Tweet.bind 'refresh', @addAll
  addOne: (tweet) =>
    tweet = new TweetItemDiv(data: tweet)
    @append(tweet.render())
  addAll: =>
    Tweet.each(@addOne)

class Form extends Spine.Controller
  events:
    'submit form': '_submitHandler'
  elements:
    'form': 'form'
    'input[type=text]': 'query'
  constructor: ->
    super
    if @initialQuery then @val(@initialQuery)
  _submitHandler: (e) =>
    e.preventDefault()
    query = @query.val()
    @trigger 'submit', query
  val: (query) ->
    @query.val(query)

# ============================================
# \(^o^)/
# ============================================

deck.load().done ->
  $ ->
    initialQuery = 'hoge'
    TweetsDiv = new TweetsDiv(el: '#tweets')
    form = new Form(el: '#searchform', initialQuery: initialQuery)
    form.bind 'submit', (query) ->
      Tweet.knock(query)
    Tweet.bind 'noresults', -> alert 'no results!'
    Tweet.knock(initialQuery)

やっとできたしclient MVCわかってきたー。

blog comments powered by Disqus

  1. atm09tdhamalogからリブログしました
  2. hamalogの投稿です