Nestable Processes Mutate

    dom-behavior

    1.2.1 • Public • Published

    dom-behavior

    browser support

    Define javascript behavior for DOM elements.

    Install

    NPM

    Example

    <html>
      <head>
        <title>Example Page</title>
      </head>
      <body>
        <div>
          Some content <button data-behavior='edit anotherBehavior'>Edit</button>
        </div>
        <div id='link' data-href='/test' data-behavior='link'>
          I'm not a link but I act like one
        </div>
      </body>
    </body>
    var behave = require('dom-behavior')
     
    var behaviors = {
      edit: function(element){
        element.onclick = function(){
          // activate editor
        }
      },
      link: function(element){
        // create a fake hyperlink
     
        var url = element.getAttribute('data-href')
        element.style.cursor = 'pointer'
     
        element.onclick = function(e){
          window.location = url
        }
     
        return function(message){
          if (message == 'update'){
            url = element.getAttribute('data-href')
            if (url){
              element.style.cursor = 'pointer'
            } else {
              element.style.cursor = 'default'
            }
          }
        }
      },
      anotherBehavior: function(element){
        // multiple behaviors can be added to the same element 
        // seperated by spaces. Just like html classes.
      }
    }
     
    var notify = behave(behaviors, document)
     
    var linkDiv = document.getElementById('link')
    linkDiv.setAttribute('data-href', '/new-url')
     
    // normally this would be called from some data-binding/templating thingy.
    // triggers func('change') on any behaviors directly on this node
    notify('update', linkDiv)
     
    // triggers func('change') on any child of this node with behaviors
    notify('inner', linkDiv)
     
    // remove behaviors and trigger func('remove')
    notify('remove', linkDiv)

    Using with become, json-context and rincewind

    See https://github.com/mmckegg/realtime-blog-example-with-browserify.

    Install

    npm i dom-behavior

    DownloadsWeekly Downloads

    25

    Version

    1.2.1

    License

    MIT

    Unpacked Size

    9.5 kB

    Total Files

    4

    Last publish

    Collaborators

    • mmckegg