• Stars
    star
    127
  • Rank 282,790 (Top 6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 11 years ago
  • Updated almost 8 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Tiny framework for web pages to split your app to separated blocks

Evil Blocks Build Status

Evil Block is a tiny JS framework for web pages. It is based on 4 ideas:

  • Split code to independent blocks. “Divide and conquer” is always good idea.
  • Blocks communicate by events. Events is an easy and safe method to keep complicated dependencies between controls very clean.
  • Separate JS and CSS. You should only use classes for styles and bind JS by special attribute selectors. This way you can update your styles without fear to break any scripts.
  • Try not to render on client. 2-way data-binding looks very cool, but it has a big price. Most of web pages (unlike web applications) can render all HTML on server and use client rendering only in few places. Without rendering we can have incredibly clean code and architecture.

See also Evil Front, a pack of helpers for Ruby on Rails and Evil Blocks.

Role aliases were taken from Role.js. Based on Pieces.js by @chrome.

Sponsored by Evil Martians

Quick Example

Slim template:

.todo-control@@todo
  ul@tasks

    - @tasks.each do |task|
      .task@task
        = task.name
        form@finishForm action="/tasks/#{ task.id }/finish"
          input type="submit" value="Finish"

  form@addForm action="/tasks/"
    input type="text"   name="name"
    input type="submit" value="Add"

Block’s CoffeeScript:

evil.block '@@todo',

  ajaxSubmit: (e) ->
    e.preventDefault()

    form = e.el
    form.addClass('is-loading')

    $.ajax
      url:      form.attr('action')
      data:     form.serialize()
      complete: -> form.removeClass('is-loading')

  'submit on @finishForm': (e) ->
    @ajaxSubmit(e).done ->
      e.el.closest("@task").addClass("is-finished")

  'submit on @addForm': (e) ->
    e.preventDefault()
    @ajaxSubmit(e).done (newTaskHTML) ->
      @tasks.append(newTaskHTML)

Attributes

If you use classes selectors in CSS and JS, your scripts will be depend on styles. If you change .small-button to .big-button, you must change all the button’s selectors in scripts.

Separated scripts and styles are better, so Evil Blocks prefers to work with two HTML attributes to bind your JS: data-block (to define blocks) and data-role (to define elements inside block).

<div data-block="todo">
    <ul data-role="tasks">
    </ul>
</div>

Evil Blocks extends Slim and jQuery, so you can use shortcuts for these attributes: @@block and @role. For Haml you can use Role Block Haml gem to use the same shortcuts.

@@todo
  ul@tasks
$('@tasks')

With these attributes you can easily change interface style and be sure in scripts:

.big-button@addButton

Of course, Evil Block doesn’t force you to write only these selectors. You can use any attributes, that you like.

Blocks

You should split your interface into independent controls and mark them with data-block:

header@@header
  a.exit href="#"

.todo-control@@todo
  ul.tasks

.docs-page@@docs

Also you can vitalize your blocks in scripts with evil.block function:

evil.block '@@header',

  init: ->
    console.log('Vitalize', @block)

When a page was loaded Evil Blocks finds blocks by @@header selector (this is a shortcut for [data-block=header]) and calls init on every founded block. So, if your page contains two headers, init will be called twice with different @block’s.

The @block property will contain a jQuery node of current block. You can search elements inside of current block with @$(selector) method:

evil.block '@@docs',

  init: ->
    @$('a').attr(target: '_blank') # Open all links inside docs in new tab
                                   # Same as @block.find('a')

You can add any methods and properties to your block class:

evil.block '@@gallery',
  current: 0

  showPhoto: (num) ->
    @$('img').hide().
      filter("eql(#{ num })").show()

  init: ->
    @showPhoto(@current)

Evil Blocks will automatically create properties with jQuery nodes for every element inside of a block with data-role attribute:

.todo-control@@todo
  ul.tasks@tasks
evil.block '@@todo',

  addTask: (task) ->
    @tasks.append(task)

If you add new HTML with AJAX, you can vitalize new blocks with evil.block.vitalize(). This function will vitalize only new blocks in a document.

@sections.append(html)
evil.block.vitalize()

Events

You can bind listeners to events inside of a block with events on selectors method:

evil.block '@@todo',

  'submit on @finishForm': ->
    # Event listener

A more difficult example:

evil.block '@@form',
  ajaxSearch: ->'change, keyup on input, select': (event) ->
    field = event.el()
    @ajaxSearch('Changed', field.val())

Listener will receive a jQuery Event object as the first argument. Current element (this in jQuery listeners) will be contained in event.el property. All listeners are delegated on current block, so click on @button is equal to @block.on 'click', '@button', ->.

You should prevent default event behavior with event.preventDefault(), return false will not do anything in block’s listeners. I recommend evil-front/links to prevent default behavior in any links with href="#" to clean your code.

You can also bind events on body and window:

evil.blocks '@@docs',
  recalcMenu: ->openPage:   ->init: ->
    @recalcMenu()

  'resize on window': ->
    @recalcMenu()

  'hashchange on window': ->
    @openPage(location.hash)

Listener load on window will execute immediately, if window is already loaded.

Blocks Communications

Blocks should communicate via custom jQuery events. You can bind an event listener to a block node with on events method:

evil.block '@@slideshow',
  nextSlide: ->'on play': ->
    @timer = setInterval(=> @nextSlide, 5000)

  'on stop': ->
    clearInterval(@timer)

evil.block '@@video',

  'click on @fullscreenButton': ->
    $('@@slideshow').trigger('stop')

If you want to use broadcast messages, you can use custom events on body:

evil.block '@@callUs',

  'change-city on body': (e, city) ->
    @phoneNumber.text(city.phone)

evil.block '@@cityChanger',
  getCurrentCity: ->'change on @citySelect': ->
    $('body').trigger('change-city', @getCurrentCity())

Rendering

If you render on the client and on the server-side, you must repeat helpers, i18n, templates. Client rendering requires a lot of libraries and architecture. 2-way data binding looks cool, but has a very big price in performance, templates, animation and overengeniring.

If you develop a web page (not a web application with offline support, etc), server-side rendering will be more useful. Users will see your interface imminently, search engines will index your content and your code will be much simple and clear.

In most of cases you can avoid client-side rendering. If you need to add a block with JS, you can render it hidden to page HTML and show it in right time:

evil.block '@@comment',

  'click on @addCommentButton': ->
    @newCommentForm.slideDown()

If a user changes some data and you need to update the view, you anyway need to send a request to save the new data on a server. Just ask the server to render a new view. For example, on a new comment server can return new comment HTML:

evil.block '@@comment',

  'submit on @addCommentForm': ->
    $.post '/comments', @addCommentForm.serialize(), (newComment) ->
      @comments.append(newComment)

But, of course, some cases require client-side rendering. Evil Blocks only recommends to do it on the server side, but not force you:

evil.block '@@comment',

  'change, keyup on @commentField', ->
    html = JST['comment'](text: @commentField.text())
    @preview.html(html)

Debug

Evil Blocks contains a debug extension, which logs all the events inside blocks. To enable it, just load evil-blocks-debug.js. For example, in Rails:

- if Rails.env.development?
  = javascript_include_tag 'evil-blocks-debug'

Extensions

Evil Blocks has a tiny core. It only finds blocks via selectors, sets the @block property and calls the init method. Any other features (like event bindings or @$() method) are created by filters and can be disabled or replaced.

Before calling init, Evil Blocks processes an object through the filters list in evil.block.filters. A filter accepts an object as its first argument and an unique class ID as the second. It can find some properties inside of the object, work with block DOM nodes and add/remove some object properties. If filter returns false, Evil Blocks will stop block vitalizing and will not call the init method.

Default filters:

  1. Don’t vitalize same DOM node twice. It returns false if a block was already initialized with a given ID.
  2. Add @$() method. It adds a shortcut find method to an object.
  3. Add shortcuts to @element. It adds properties for all children with data-role attribute.
  4. Bind block events. Find, bind listeners and remove all the methods with a name like on event.
  5. Smarter window load listener. Run load on window listener immediately, if window is already loaded.
  6. Bind window and body events. Find, bind listeners and remove all the methods with a name like event on window or event on body.
  7. Bind elements events. Find, bind listeners and remove all the methods with a name like event on child.

You can add you own filter to evil.block.filters. Most filters should be added after first filter to not been called on already initialized blocks.

Let’s write filter, which will initialize blocks only when they become to be visible.

filter = (obj) ->
  if not obj.block.is(':visible')
    # Check for visibility every 100 ms
    # and recall vitalizing if block become visible
    checking = ->
      evil.block.vitalize(obj.block) if obj.block.is(':visible')
    setTimeout(checking, 100);

    # Disable block initializing
    return false

# Add filter to list
evil.block.filters.splice(0, 0, filter)

With the filters you can change Evil Blocks logic, add some new shortcuts or features like mixins.

Also you can remove any default filters from evil.block.filters. For example, you can create properties for data-role children only from some white list.

But Filters API is still unstable and you should be careful on major updates.

Modules

If your blocks have same behavior, you can create a module-block and set multiple blocks on the same tag:

@popup@@closable
  a@closeLink href="#"
evil.block '@@closable',

  'click on @closeLink': ->
    @block.trigger('close')

evil.block '@@popup',

  'on close': ->
    @block.removeClass('is-open')

If you want to use same methods inside of multiple block, you can create an inject-function:

fancybox = (obj) ->
  for name, value of fancybox.module
    obj[name] = value
  # Initializer code

fancybox.module =
  openInFancybox: (node) ->

evil.block '@@docs',

  init: ->
    fancybox(@)

  'click on @showExampleButton': ->
    @openInFancybox(@example)

Install

Ruby on Rails

Add evil-block-rails gem to Gemfile:

gem "evil-blocks-rails"

Load evil-blocks.js in your script:

//= require evil-blocks

If you use Rails 3 on Heroku, you may need some hack.

Ruby

If you use Sinatra or other non-Rails framework you can add Evil Blocks path to Sprockets environment:

EvilBlocks.install(sprockets)

And change Slim options to support @@block and @rule shortcuts:

EvilBlocks.install_to_slim!

Then just load evil-blocks.js in your script:

//= require evil-blocks

Others

Add file lib/evil-blocks.js to your project.

More Repositories

1

nanoid

A tiny (124 bytes), secure, URL-friendly, unique string ID generator for JavaScript
JavaScript
24,064
star
2

easings.net

Easing Functions Cheat Sheet
CSS
7,908
star
3

size-limit

Calculate the real cost to run your JS app or lib to keep good performance. Show error in pull request if the cost exceeds the limit.
JavaScript
6,487
star
4

visibilityjs

Wrapper for the Page Visibility API
JavaScript
1,825
star
5

nanoevents

Simple and tiny (107 bytes) event emitter library for JavaScript
TypeScript
1,442
star
6

autoprefixer-rails

Autoprefixer for Ruby and Ruby on Rails
Ruby
1,213
star
7

nanocolors

Use picocolors instead. It is 3 times smaller and 50% faster.
JavaScript
868
star
8

audio-recorder-polyfill

MediaRecorder polyfill to record audio in Edge and Safari
JavaScript
580
star
9

keyux

JS library to improve keyboard UI of web apps
TypeScript
380
star
10

webp-in-css

PostCSS plugin and tiny JS script (131 bytes) to use WebP in CSS background
JavaScript
346
star
11

offscreen-canvas

Polyfill for OffscreenCanvas to move Three.js/WebGL/2D canvas to Web Worker
JavaScript
332
star
12

convert-layout

JS library to convert text from one keyboard layout to other
JavaScript
251
star
13

ssdeploy

Netlify replacement to deploy simple websites with better flexibility, speed and without vendor lock-in
JavaScript
194
star
14

environment

My home config, scripts and installation process
Shell
193
star
15

nanodelay

A tiny (37 bytes) Promise wrapper around setTimeout
JavaScript
189
star
16

dual-publish

Publish JS project as dual ES modules and CommonJS package to npm
JavaScript
186
star
17

nanospy

Spy and mock methods in tests with great TypeScript support
TypeScript
138
star
18

check-dts

Unit tests for TypeScript definitions in your JS open source library
JavaScript
138
star
19

autoprefixer-core

autoprefixer-core was depreacted, use autoprefixer
JavaScript
136
star
20

transition-events

jQuery plugin to set listeners to CSS Transition animation end or specific part
JavaScript
133
star
21

rails-sass-images

Sass functions and mixins to inline images and get images size
Ruby
114
star
22

compass.js

Compass.js allow you to get compass heading in JavaScript by PhoneGap, iOS API or GPS hack.
CoffeeScript
112
star
23

evil-front

Helpers for frontend from Evil Martians
Ruby
101
star
24

rake-completion

Bash completion support for Rake
Shell
63
star
25

yaspeller-ci

Fast spelling check for Travis CI
JavaScript
61
star
26

jquery-cdn

Best way to use latest jQuery in Ruby app
Ruby
59
star
27

sitnik.ru

My homepage content and scripts
JavaScript
57
star
28

pages.js

CoffeeScript
44
star
29

fotoramajs

Fotorama for Ruby on Rails
Ruby
44
star
30

about-postcss

Keynotes about PostCSS
Ruby
29
star
31

autohide-battery

GNOME Shell extension to hide battery icon in top panel, if battery is fully charged and AC is connected.
JavaScript
28
star
32

darian

Darian Mars calendar converter
Ruby
25
star
33

better-node-test

The CLI shortcut for node --test runner with TypeScript
JavaScript
25
star
34

plain_record

Data persistence with human readable and editable storage.
Ruby
24
star
35

evolu-lang

Programming language to automatically generate programs by evolution (genetic programming).
JavaScript
22
star
36

martian-logux-demo

TypeScript
17
star
37

hide-keyboard-layout

GNOME Shell extension to hide keyboard layout indicator in status bar
JavaScript
17
star
38

twitter2vk

Script to automatically repost statuses from Twitter to VK (В Контакте)
Ruby
16
star
39

asdf-cache-action

A Github Action to install runtimes by asdf CLI with a cache
15
star
40

ci-job-number

Return CI job number to run huge tests only on first job
JavaScript
15
star
41

print-snapshots

Print Jest snapshots to check CLI output of your tool
JavaScript
15
star
42

load-resources

Load all JS/CSS files from site website
JavaScript
15
star
43

susedko

Fedora CoreOS ignition config for my home server
JavaScript
14
star
44

file-container

Store different languages in one source file
JavaScript
14
star
45

postcss-isolation

Fix global CSS with PostCSS
14
star
46

autoprefixer-cli

CLI for Autoprefixer
JavaScript
14
star
47

d2na

D²NA language for genetic programming
Ruby
11
star
48

showbox

Keynote generator
JavaScript
11
star
49

boilerplates

Boilerplate for my open source projects
JavaScript
9
star
50

postcss-way

Keynotes about PostCSS way
9
star
51

gulp-bench-summary

Display gulp-bench results in nice table view
JavaScript
8
star
52

universal-layout

Универсальная раскладка Ситника
8
star
53

anim2012

Доклад «Анимации по-новому — лень, гордыня и нетерпимость»
CSS
8
star
54

nanopurify

A tiny (from 337 bytes) HTML sanitizer
JavaScript
7
star
55

ai

6
star
56

rit3d

Доклад «Веб, теперь в 3D: Практика»
CSS
6
star
57

dis.spbstu.ru

Department homepage
Ruby
5
star
58

jstransformer-lowlight

Lowlight support for JSTransformers
JavaScript
5
star
59

jest-ci

CLI for Jest test framework, but coverage only on first CI job
JavaScript
5
star
60

evolu-steam

Evolu Steam – evolutionary computation for JavaScript
JavaScript
5
star
61

insomnis

Текст блогокниги «Инсомнис»
4
star
62

plague

Blog/book Plague engine
Ruby
4
star
63

wsd2013

Презентация «Автопрефиксер: мир без CSS-префиксов»
Ruby
4
star
64

showbox-bright

Shower Bright theme for Showbox
JavaScript
3
star
65

ruby2jar

Ruby2Jar builds JAR from a Ruby script
Ruby
3
star
66

showbox-ai

Sitnik’s theme for ShowBox
CSS
3
star
67

showbox-shower

Shower for ShowBox
JavaScript
2
star
68

on_the_islands

Ruby
2
star