JSFiddle - React, Tailwind, and code Playground
by jamz
HTML
<input
type="button"
class="clearSomeEls"
data-clearSel=".testList li"
value="clear a random number of li elements"
>
<ul class="testList">
<!-- Start empty, we'll add list elements -->
</ul>
<input
type="button"
class="clearSomeEls"
data-clearSel=".testParagraphs p"
value="clear a random number of p elements"
>
<div class="testParagraphs">
<!-- Start empty, we'll add list elements -->
</div>
CoffeeScript
# Revealing Module pattern in CoffeeScript with hidden classes
# ============================================================
#
# This example shows how to poll for UI conditions in a reusable way.
# It's an adaptation of something I came up with for an app I'm building,
# just created here in a more playful manner to test first.
#
# The way it's set up, there should be a maximum of 7 list item elements
# in any given container element. As soon as fewer than 7 exist, the script
# will create the missing elements, one per second.
RM = do ->
class uiCondition
addCondition: (func, args) ->
t = ->
setTimeout ->
func.apply this, args
t()
, 1000
t()
constructor: (func, args) ->
@addCondition func, args
{
# Calling this should run the function to check the condition every
# second. Direct access to uiCondition is unavailable, as you can see
# if you look in the browser console.
registerCondition: (func, args) ->
c = new uiCondition func, args
}
# The condition to poll for and the action to take
i = 1
produceUntilSeven = (containerSel, innerEl) ->
listLen = $("#{containerSel} #{innerEl}").length
content = "#{i} total elements added"
if listLen < 7
$(containerSel).prepend $("<#{innerEl}/>").text(content)
i++
# Button handler to delete a random number of elements from the list
$('.clearSomeEls').click ->
clearSel = $(this).attr('data-clearSel') # Use .attr() instead of .data() to get as string
console.log clearSel
n = Math.floor(Math.random() * $(clearSel).length) + 1
for index in [1...n]
$(clearSel).eq(index).remove()
# Call the exposed method to run the example
# This can be called on as many elements as desired, just pass in the args array
RM.registerCondition produceUntilSeven, ['.testList', 'li']
RM.registerCondition...