JSFiddle - React, Tailwind, and code Playground

by chridam

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min.js"></script>
<div class='test'>
    <input class="search-conditions" id="search"/>       
</div>

CoffeeScript

ItemView = Backbone.View.extend
	tagName: 'li'
	template: "<a class='select-item'><%= label %></a>"
	events:
		'click .select-item': 'select'
	render: ->
		@$el.html _.template(@template,
			label: @model.label()
		)

		this
	select: (e)->		
		@$el.hide()
		e.preventDefault()
		false

SearchView = Backbone.View.extend
	tagName: 'ul'
	className: 'search-items' 
	currentText: ''
	wait: 100
	render: ->
		@input.attr 'autocomplete', 'off'
		@$el.width @input.outerWidth()		
		@input.keyup(@keyup.bind(this)).after @$el

		this

	events:
		'keyup .search-conditions': 'keyup'

	initialize: (options) ->
		_.extend this, options
		@filter = _.debounce(@filter, @wait)

	keyup: ->
		keyword = @input.val()
		if @isChanged(keyword)
			if @isValid(keyword)
				@filter keyword
			else
				@hide()         

	filter: (keyword) ->
		keyword = keyword.toLowerCase()
		self = this
		@model.reset()
		url = "https://api.howareyou.com/conditions/search.json?term=#{keyword}"
		$.getJSON url, (data) ->							
			models = data.map((m) -> new SearchModel(m))  
			self.model.reset models		
			self.loadResult self.model.models, keyword

	isValid: (keyword) ->
		keyword.length > 2

	isChanged: (keyword) ->
		@currentText isnt keyword

	loadResult: (model, keyword) ->
		@currentText = keyword
		@reset()				
		if model.length
			_.forEach model, @addItem, this
			@show()
		else
			@hide()

	addItem: (model) ->
		
		@$el.append new ItemView(
			model: model
			parent: this
		).render().$el

	show: ->
		@$el.show()
		this

	hide: ->
		@$el.hide()
		this

	reset: ->
		@$el.empty()
		this		

SearchCollection = Backbone.Collection.extend
	model: SearchModel

	initialize: (models, options) ->
		_.extend this, models, options

SearchModel = Backbone.Model.extend
	idAttribute: 'id'
	defaults: ->
		snomed_concept_id = ''
		term: ''
		synonyms: undefined
	conceptId: ->
		@get 'snomed_concept_id'
	value: ->
		@get 'id'
	label: ->
		@get 'term'
	synonyms: ->
		@get 'synonyms'	
	initialize: (options)...