{"id":16347936,"url":"https://github.com/ai/evil-blocks","last_synced_at":"2025-04-06T10:14:31.179Z","repository":{"id":56845035,"uuid":"9755246","full_name":"ai/evil-blocks","owner":"ai","description":"Tiny framework for web pages to split your app to separated blocks","archived":false,"fork":false,"pushed_at":"2016-11-15T01:01:46.000Z","size":127,"stargazers_count":132,"open_issues_count":4,"forks_count":10,"subscribers_count":7,"default_branch":"master","last_synced_at":"2025-03-30T09:08:53.684Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ai.png","metadata":{"files":{"readme":"README.md","changelog":"ChangeLog.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2013-04-29T18:40:26.000Z","updated_at":"2025-01-01T21:49:41.000Z","dependencies_parsed_at":"2022-08-30T14:50:14.743Z","dependency_job_id":null,"html_url":"https://github.com/ai/evil-blocks","commit_stats":null,"previous_names":[],"tags_count":16,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ai%2Fevil-blocks","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ai%2Fevil-blocks/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ai%2Fevil-blocks/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ai%2Fevil-blocks/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ai","download_url":"https://codeload.github.com/ai/evil-blocks/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247464226,"owners_count":20942970,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-11T00:47:15.307Z","updated_at":"2025-04-06T10:14:31.160Z","avatar_url":"https://github.com/ai.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Evil Blocks [![Build Status](https://travis-ci.org/ai/evil-blocks.svg)](https://travis-ci.org/ai/evil-blocks)\n\n\u003cimg align=\"right\" width=\"140\" height=\"115\" src=\"http://ai.github.io/evil-blocks/logo.svg\" title=\"Evil Blocks logo by Roman Shamin\"\u003e\n\nEvil Block is a tiny JS framework for web pages. It is based on 4 ideas:\n\n* **Split code to independent blocks.** “Divide and conquer” is always good idea.\n* **Blocks communicate by events.** Events is an easy and safe method\n  to keep complicated dependencies between controls very clean.\n* **Separate JS and CSS.** You should only use classes for styles and bind JS\n  by special attribute selectors. This way you can update your styles without\n  fear to break any scripts.\n* **Try not to render on client.** 2-way data-binding looks very cool,\n  but it has a [big price]. Most of web pages (unlike web applications)\n  can render all HTML on server and use client rendering only in few places.\n  Without rendering we can have incredibly clean code and architecture.\n\nSee also [Evil Front], a pack of helpers for Ruby on Rails and Evil Blocks.\n\nRole aliases were taken from [Role.js]. Based on Pieces.js by [@chrome].\n\n\u003ca href=\"https://evilmartians.com/?utm_source=evil-blocks\"\u003e\n\u003cimg src=\"https://evilmartians.com/badges/sponsored-by-evil-martians.svg\" alt=\"Sponsored by Evil Martians\" width=\"236\" height=\"54\"\u003e\n\u003c/a\u003e\n\n[Role.js]:       https://github.com/kossnocorp/role\n[big price]:     http://staal.io/blog/2014/02/05/2-way-data-binding-under-the-microscope/\n[Evil Front]:    https://github.com/ai/evil-front\n[@chrome]:       https://github.com/chrome\n\n## Quick Example\n\nSlim template:\n\n```haml\n.todo-control@@todo\n  ul@tasks\n\n    - @tasks.each do |task|\n      .task@task\n        = task.name\n        form@finishForm action=\"/tasks/#{ task.id }/finish\"\n          input type=\"submit\" value=\"Finish\"\n\n  form@addForm action=\"/tasks/\"\n    input type=\"text\"   name=\"name\"\n    input type=\"submit\" value=\"Add\"\n```\n\nBlock’s CoffeeScript:\n\n```coffee\nevil.block '@@todo',\n\n  ajaxSubmit: (e) -\u003e\n    e.preventDefault()\n\n    form = e.el\n    form.addClass('is-loading')\n\n    $.ajax\n      url:      form.attr('action')\n      data:     form.serialize()\n      complete: -\u003e form.removeClass('is-loading')\n\n  'submit on @finishForm': (e) -\u003e\n    @ajaxSubmit(e).done -\u003e\n      e.el.closest(\"@task\").addClass(\"is-finished\")\n\n  'submit on @addForm': (e) -\u003e\n    e.preventDefault()\n    @ajaxSubmit(e).done (newTaskHTML) -\u003e\n      @tasks.append(newTaskHTML)\n```\n\n## Attributes\n\nIf you use classes selectors in CSS and JS, your scripts will be depend\non styles. If you change `.small-button` to `.big-button`, you must\nchange all the button’s selectors in scripts.\n\nSeparated scripts and styles are better, so Evil Blocks prefers to work with\ntwo HTML attributes to bind your JS: `data-block` (to define blocks)\nand `data-role` (to define elements inside block).\n\n```html\n\u003cdiv data-block=\"todo\"\u003e\n    \u003cul data-role=\"tasks\"\u003e\n    \u003c/ul\u003e\n\u003c/div\u003e\n```\n\nEvil Blocks extends Slim and jQuery, so you can use shortcuts for these\nattributes: `@@block` and `@role`. For Haml you can use [Role Block Haml] gem\nto use the same shortcuts.\n\n```haml\n@@todo\n  ul@tasks\n```\n\n```js\n$('@tasks')\n```\n\nWith these attributes you can easily change interface style\nand be sure in scripts:\n\n```haml\n.big-button@addButton\n```\n\nOf course, Evil Block doesn’t force you to write only these selectors.\nYou can use any attributes, that you like.\n\n[Role Block Haml]: https://github.com/vladson/role_block_haml\n\n## Blocks\n\nYou should split your interface into independent controls and mark them\nwith `data-block`:\n\n```haml\nheader@@header\n  a.exit href=\"#\"\n\n.todo-control@@todo\n  ul.tasks\n\n.docs-page@@docs\n```\n\nAlso you can vitalize your blocks in scripts with `evil.block` function:\n\n```coffee\nevil.block '@@header',\n\n  init: -\u003e\n    console.log('Vitalize', @block)\n```\n\nWhen a page was loaded Evil Blocks finds blocks by `@@header` selector\n(this is a shortcut for `[data-block=header]`) and calls `init` on every\nfounded block. So, if your page contains two headers, `init` will be called\ntwice with different `@block`’s.\n\nThe `@block` property will contain a jQuery node of current block.\nYou can search elements inside of current block with `@$(selector)` method:\n\n```coffee\nevil.block '@@docs',\n\n  init: -\u003e\n    @$('a').attr(target: '_blank') # Open all links inside docs in new tab\n                                   # Same as @block.find('a')\n```\n\nYou can add any methods and properties to your block class:\n\n```coffee\nevil.block '@@gallery',\n  current: 0\n\n  showPhoto: (num) -\u003e\n    @$('img').hide().\n      filter(\"eql(#{ num })\").show()\n\n  init: -\u003e\n    @showPhoto(@current)\n```\n\nEvil Blocks will automatically create properties with jQuery nodes\nfor every element inside of a block with `data-role` attribute:\n\n```haml\n.todo-control@@todo\n  ul.tasks@tasks\n```\n\n```coffee\nevil.block '@@todo',\n\n  addTask: (task) -\u003e\n    @tasks.append(task)\n```\n\nIf you add new HTML with AJAX, you can vitalize new blocks with\n`evil.block.vitalize()`. This function will vitalize only new blocks in\na document.\n\n```coffee\n@sections.append(html)\nevil.block.vitalize()\n```\n\n## Events\n\nYou can bind listeners to events inside of a block with `events on selectors`\nmethod:\n\n```coffee\nevil.block '@@todo',\n\n  'submit on @finishForm': -\u003e\n    # Event listener\n```\n\nA more difficult example:\n\n```coffee\nevil.block '@@form',\n  ajaxSearch: -\u003e …\n\n  'change, keyup on input, select': (event) -\u003e\n    field = event.el()\n    @ajaxSearch('Changed', field.val())\n```\n\nListener will receive a jQuery Event object as the first argument.\nCurrent element (`this` in jQuery listeners) will be contained in `event.el`\nproperty. All listeners are delegated on current block, so `click on @button`\nis equal to `@block.on 'click', '@button', -\u003e`.\n\nYou should prevent default event behavior with `event.preventDefault()`,\n`return false` will not do anything in block’s listeners. I recommend\n[evil-front/links] to prevent default behavior in any links with `href=\"#\"`\nto clean your code.\n\nYou can also bind events on body and window:\n\n```coffee\nevil.blocks '@@docs',\n  recalcMenu: -\u003e …\n  openPage:   -\u003e …\n\n  init: -\u003e\n    @recalcMenu()\n\n  'resize on window': -\u003e\n    @recalcMenu()\n\n  'hashchange on window': -\u003e\n    @openPage(location.hash)\n```\n\nListener `load on window` will execute immediately, if window is already loaded.\n\n[evil-front/links]: https://github.com/ai/evil-front/blob/master/evil-front/lib/assets/javascripts/evil-front/links.js\n\n## Blocks Communications\n\nBlocks should communicate via custom jQuery events. You can bind an event\nlistener to a block node with `on events` method:\n\n```coffee\nevil.block '@@slideshow',\n  nextSlide: -\u003e …\n\n  'on play': -\u003e\n    @timer = setInterval(=\u003e @nextSlide, 5000)\n\n  'on stop': -\u003e\n    clearInterval(@timer)\n\nevil.block '@@video',\n\n  'click on @fullscreenButton': -\u003e\n    $('@@slideshow').trigger('stop')\n```\n\nIf you want to use broadcast messages, you can use custom events on body:\n\n```coffee\nevil.block '@@callUs',\n\n  'change-city on body': (e, city) -\u003e\n    @phoneNumber.text(city.phone)\n\nevil.block '@@cityChanger',\n  getCurrentCity: -\u003e …\n\n  'change on @citySelect': -\u003e\n    $('body').trigger('change-city', @getCurrentCity())\n```\n\n## Rendering\n\nIf you render on the client and on the server-side, you must repeat helpers,\ni18n, templates. Client rendering requires a lot of libraries and architecture.\n2-way data binding looks cool, but has a very [big price] in performance,\ntemplates, animation and overengeniring.\n\nIf you develop a web page (not a web application with offline support, etc),\nserver-side rendering will be more useful. Users will see your interface\nimminently, search engines will index your content and your code will be much\nsimple and clear.\n\nIn most of cases you can avoid client-side rendering. If you need to add a block\nwith JS, you can render it hidden to page HTML and show it in right time:\n\n```coffee\nevil.block '@@comment',\n\n  'click on @addCommentButton': -\u003e\n    @newCommentForm.slideDown()\n```\n\nIf a user changes some data and you need to update the view, you anyway need\nto send a request to save the new data on a server. Just ask the server\nto render a new view. For example, on a new comment server can return\nnew comment HTML:\n\n```coffee\nevil.block '@@comment',\n\n  'submit on @addCommentForm': -\u003e\n    $.post '/comments', @addCommentForm.serialize(), (newComment) -\u003e\n      @comments.append(newComment)\n```\n\nBut, of course, some cases require client-side rendering. Evil Blocks only\nrecommends to do it on the server side, but not force you:\n\n```coffee\nevil.block '@@comment',\n\n  'change, keyup on @commentField', -\u003e\n    html = JST['comment'](text: @commentField.text())\n    @preview.html(html)\n```\n\n[big price]: http://staal.io/blog/2014/02/05/2-way-data-binding-under-the-microscope/\n\n## Debug\n\nEvil Blocks contains a debug extension, which logs all the events inside blocks.\nTo enable it, just load `evil-blocks-debug.js`. For example, in Rails:\n\n```haml\n- if Rails.env.development?\n  = javascript_include_tag 'evil-blocks-debug'\n```\n\n## Extensions\n\nEvil Blocks has a tiny core. It only finds blocks via selectors,\nsets the `@block` property and calls the `init` method. Any other features\n(like event bindings or `@$()` method) are created by filters\nand can be disabled or replaced.\n\nBefore calling `init`, Evil Blocks processes an object through the filters list\nin `evil.block.filters`. A filter accepts an object as its first argument and\nan unique class ID as the second. It can find some properties inside of\nthe object, work with block DOM nodes and add/remove some object properties.\nIf filter returns `false`, Evil Blocks will stop block vitalizing\nand will not call the `init` method.\n\nDefault filters:\n\n1. **Don’t vitalize same DOM node twice.** It returns `false` if a block\n   was already initialized with a given ID.\n2. **Add `@$()` method.** It adds a shortcut find method to an object.\n3. **Add shortcuts to `@element`.** It adds properties for all children with\n   `data-role` attribute.\n4. **Bind block events.** Find, bind listeners and remove all the methods with\n   a name like `on event`.\n5. **Smarter window load listener.** Run `load on window` listener immediately,\n   if window is already loaded.\n6. **Bind window and body events.** Find, bind listeners and remove all\n   the methods with a name like `event on window` or `event on body`.\n7. **Bind elements events.** Find, bind listeners and remove all the methods\n   with a name like `event on child`.\n\nYou can add you own filter to `evil.block.filters`. Most filters should be added\nafter first filter to not been called on already initialized blocks.\n\nLet’s write filter, which will initialize blocks only when they become\nto be visible.\n\n```coffee\nfilter = (obj) -\u003e\n  if not obj.block.is(':visible')\n    # Check for visibility every 100 ms\n    # and recall vitalizing if block become visible\n    checking = -\u003e\n      evil.block.vitalize(obj.block) if obj.block.is(':visible')\n    setTimeout(checking, 100);\n\n    # Disable block initializing\n    return false\n\n# Add filter to list\nevil.block.filters.splice(0, 0, filter)\n```\n\nWith the filters you can change Evil Blocks logic, add some new shortcuts\nor features like mixins.\n\nAlso you can remove any default filters from `evil.block.filters`. For example,\nyou can create properties for `data-role` children only from some white list.\n\nBut Filters API is still unstable and you should be careful on major updates.\n\n## Modules\n\nIf your blocks have same behavior, you can create a module-block\nand set multiple blocks on the same tag:\n\n```haml\n@popup@@closable\n  a@closeLink href=\"#\"\n```\n\n```coffee\nevil.block '@@closable',\n\n  'click on @closeLink': -\u003e\n    @block.trigger('close')\n\nevil.block '@@popup',\n\n  'on close': -\u003e\n    @block.removeClass('is-open')\n```\n\nIf you want to use same methods inside of multiple block, you can create\nan inject-function:\n\n```coffee\nfancybox = (obj) -\u003e\n  for name, value of fancybox.module\n    obj[name] = value\n  # Initializer code\n\nfancybox.module =\n  openInFancybox: (node) -\u003e\n\nevil.block '@@docs',\n\n  init: -\u003e\n    fancybox(@)\n\n  'click on @showExampleButton': -\u003e\n    @openInFancybox(@example)\n```\n\n## Install\n\n### Ruby on Rails\n\nAdd `evil-block-rails` gem to `Gemfile`:\n\n```ruby\ngem \"evil-blocks-rails\"\n```\n\nLoad `evil-blocks.js` in your script:\n\n```js\n//= require evil-blocks\n```\n\nIf you use Rails 3 on Heroku, you may need\n[some hack](https://github.com/ai/evil-blocks/issues/17).\n\n### Ruby\n\nIf you use Sinatra or other non-Rails framework you can add Evil Blocks path\nto Sprockets environment:\n\n```ruby\nEvilBlocks.install(sprockets)\n```\n\nAnd change Slim options to support `@@block` and `@rule` shortcuts:\n\n```ruby\nEvilBlocks.install_to_slim!\n```\n\nThen just load `evil-blocks.js` in your script:\n\n```js\n//= require evil-blocks\n```\n\n### Others\n\nAdd file `lib/evil-blocks.js` to your project.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fai%2Fevil-blocks","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fai%2Fevil-blocks","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fai%2Fevil-blocks/lists"}