JSFiddle - React, Tailwind, and code Playground

by hideki_a

HTML

<script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<h1>誰が誰につぶやいた?</h1>
<h2>検索フォーム</h2>
<form action="#" method="get" id="searchform">
つぶやかれた人(例:_hideki_a)<br>
<input type="text" id="username" value="">
<input type="submit" id="submit" value="search">
</form>
<h2>検索結果</h2>
<script id="tmpl-searchresult" type="text/x-jquery-tmpl">
<ul>
{{each tweets}}
<li>
<span class="username">@${from_user}さん</span> <span class="comment">${text}</span>
</li>
{{/each}}
</ul>
</script>
<div id="searchresult"></div>

CSS

body{
    line-height:1.5;
    font-size:0.75em;
}

h1{
    margin-bottom:1em;
}

h2{
    margin-bottom:0;
}

#searchresult li span{
    display:block;
}

JavaScript

var URL_SEARCH_API = "http://search.twitter.com/search.json";
var target;

$.widget("ui.searchform", {
    _create: function() {
        var self = this;
        self.widgetEventPrefix = "searchform.";
        self.$input = $(":text", self.element);
        self.element.bind("submit", function(event) {
            event.preventDefault();
            target = self.$input.val();
            var data = {
                val: "@" + target
            };
            self._trigger("submit", event, data);
        });
    },
    reset: function() {
        this.$input.val("");
    }
});

$.widget("ui.searchresult", {
    _create: function() {
        this.widgetEventPrefix = "searchresult.";
    },
    _add: function(data) {
        $("#tmpl-searchresult").tmpl({ tweets: data })
                               .appendTo("#searchresult");
    },
    update: function(keywords) {
        var self = this;
        $.ajax({
            url: URL_SEARCH_API,
            dataType: "jsonp",
            data: {
                result_type: "recent",
                rpp: 10,
                page: 1,
                q: keywords
            }
        }).then(
            function(response) {
                self.reset();
                self._add(response.results);
            },
            function() {
                alert("Twitter Error!");
            }
        );
    },
    reset: function() {
        this.element.empty();
    }
});

$(function() {
    // 要素を変数に格納
    var $searchform = $("#searchform"),
        $searchresult = $("#searchresult");
    
    // ウィジェットを適用
    $searchform.searchform();
    $searchresult.searchresult();
    
    // イベントバインド
    $searchform.bind("searchform.submit", function(event, data) {
        $searchresult.searchresult("update", data.val);
    });
});