Coder Social home page Coder Social logo

dombuilder's Introduction

DOMBuilder travis_status qunit_tests

DOMBuilder takes some of the pain out of dynamically creating HTML content in JavaScript and supports generating multiple types of output from the same inputs.

Yes, there are a million builder libraries about. DOMBuilder's goals are to:

  • Make it easier to write JavaScript components which can be shared between the frontend and backend - newforms is an example of such a component, which aims to share validation code between the two.
  • Make it easier to switch from DOM Element output to HTML String output if performence becomes an issue, by providing mock DOM objects and event registration helpers when generating HTML from the exact same input.

Demos

  • Fragile - uses DOMBuilder's template mode and its template inheritance to create a CRUD admin with templates which can also be rendered on the backend with Node.js.
  • DOMBuilder.build() sandbox - play around with DOMBuilder.build(), with switchable DOM and HTML output modes.
  • Reddit posts - uses JSONP to display a feed of posts from Reddit:
  • Demo page - small examples of using the range of the DOMBuilder API

Install

Browsers

Compressed builds of DOMBuilder are available to suit various needs:

DOM and HTML

For creation of mixed content, with DOM Mode as the default output format.

DOM only

For creation of DOM Elements, with DOM Mode as the default output format.

HTML only

For creation of HTML Strings, with HTML Mode as the default output format.

Templates

For templating, with mixed output and DOM Mode as the default output format.

Dependencies

There are no required dependencies, but if jQuery (>= 1.4) is available, DOMBuilder will make use of it when creating DOM Elements and setting up their attributes and event handlers.

If not, DOMBuilder will fall back to using some less comprehensive workarounds for cross-browser DOM issues and use the traditional event registration model for compatibility.

Node.js

DOMBuilder can be installed as a Node.js module via npm. The Node.js build includes Template mode and has HTML mode as the default output format.

Install:

npm install DOMBuilder

Import:

var DOMBuilder = require('DOMBuilder')

Quick Guide

DOMBuilder provides a convenient, declarative API for generating HTML elements, via objects which contain functions named for the HTML element they create:

with(DOMBuilder.dom) {
  var article =
    DIV({'class': 'article'}
    , H2('Article title')
    , P('Paragraph one')
    , P('Paragraph two')
    )
}

Every element function also has a map function attached to it which allows you to easily generate content from a list of items:

var el = DOMBuilder.html
function shoppingList(items) {
  return el.OL(el.LI.map(items))
}
>>> shoppingList(['Cheese', 'Bread', 'Butter'])
<ol><li>Cheese</li><li>Bread</li><li>Butter</li></ol>

You can control map output by passing in a callback function:

function opinionatedShoppingList(items) {
  return el.OL(el.LI.map(items, function(item, attrs, loop) {
    if (item == 'Cheese') attrs['class'] = 'eww'
    if (item == 'Butter') return el.EM(item)
    return item
  }))
}
>>> opinionatedShoppingList(['Cheese', 'Bread', 'Butter'])
<ol><li class="eww">Cheese</li><li>Bread</li><li><em>Butter</em></li></ol>

If you want to use this API to go straight to a particular type of output, you can do so using the functions defined in DOMBuilder.dom and DOMBuilder.html, as demonstrated above.

If you want to be able to switch freely between output modes, or you won't know which kind of output you need until runtime, you can use the same API via DOMBuilder.elements, controlling what it outputs by setting the DOMBuilder.mode flag to 'dom' or 'html', or calling a function which generates content using DOMBuilder.withMode:

var el = DOMBuilder.elements
function shoutThing(thing) {
  return el.STRONG(thing)
}
>>> DOMBuilder.mode = 'html'
>>> shoutThing('Hello!').toString()
<strong>Hello!</strong>
>>> DOMBuilder.withMode('dom', shoutThing, 'Hey there!')
[object HTMLStrongElement]

This is useful for writing libraries which need to support outputting both DOM Elements and HTML Strings, or for unit-testing code which normally generates DOM Elements by flipping the mode in your tests to switch to HTML String output.

DOMBuilder also supports using its output modes with another common means of defining HTML in JavaScript code, using nested lists (representing elements and their contents) and objects (representing attributes), like so:

var article =
  ['div', {'class': 'article'}
  , ['h2', 'Article title']
  , ['p', 'Paragraph one']
  , ['p', 'Paragraph two']
  ]

You can generate output from one of these structures using DOMBuilder.build, specifying the output mode:

>>> DOMBuilder.build(article, 'html').toString()
<div class="article"><h2>Article title</h2><p>Paragraph one</p><p>Paragraph two</p></div>

>>> DOMBuilder.build(article, 'dom').toString()
[object HTMLDivElement]

You can also generate these kinds of structures using the element functions defined in DOMBuilder.array.

This is just a quick guide to what DOMBuilder can do - dive into the full documentation to find out about the rest of its features, such as:

Development

Version 2.1: DOMBuilder.template

DOMBuilder is a modular library, which supports adding new output modes and feature modes as plugins.

Version 2.1 will add Template mode to DOMBuilder and the templating API should be considered unstable until Version 2.2.

  • Based on Django templates, including their powerful template inheritance.
  • Templates are defined entirely in JavaScript code, still discovering the pros and cons of this as I go:

    Pros

    • Easier to create new template tags, as there's no parsing step.
    • You can spin template creation out into DSL-like functions, which is expressive and very flexible, using functions to build up sections using logically named functions which create template contents based on data structures, rather than copying and pasting chunks of annotated markup or trying to use includes.

    Cons

    • More unwieldy to edit than text-based templates, but manageable if you follow some layout guidelines.
    • More awkward to do things like optional attributes and arbitrary chunks of HTML, since HTML is defined at the element level using DOMBuilder's element functions.

In this live example, template inheritance is being used to minimise the effort required to create basic admin CRUD screens using Sacrum.

Version 2.0.1 released on August 6th, 2011

See News for DOMBuilder for what's new and backwards-incompatible changes since 1.4.*.

MIT License

Copyright (c) 2011, Jonathan Buchanan

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

dombuilder's People

Contributors

insin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dombuilder's Issues

Need a better approach to using entities in Strings

An NBSP variable has plagued DOMBuilder since it was first used to generate tables many moons ago. There are a couple of special cases in the code involving the unicode String representation of a non-breaking space.

As DOMBuilder doesn't do any HTML parsing with innerHTML, how can we make it easier to work with entities in Strings?

Event handlers and innerHTML - together at last?

Since we're always working with objects when generating HTML with DOMBuilder, make some use of them.

How about providing a method on HTMLElement which finds children which have ids and event handling Function attributes and registers events on the elements with the appropriate ids?

Users could call this method after they've toString()ed and innerHTMLed to set up all the event listeners - switching from DOM to HTML mode without changing any element creation code would then be a viable option for people looking for a speedup.

We could generate dummy ids for HTMLElements which have event listening function attributes but no id attribute to make this totally automatic as far as the user is concerned.

Providing a function which takes the element to be innerHTMLed and does both steps would make it even nicer.

DOM Templates

Goal for 2.1 - can we use the DOMBuilder API as the basis for an object-based templating system with template inheritance?

Scattershot thoughts and questions:

  • Reuse HTML mock objects in some way or introduce a new mode with its own objects which leverage the element creation function approach?
  • Strings for simple things... logic functions - can these be done non-horribly?
  • Compile step which keeps track of where logic needs to happen?
  • Dummy nodes identify places where logic needs to happen at render time?
  • Cloning as much as possible when outputting DOM elements from templates - DocumentFragments all over your face.
  • Reuse the same templates to generate DOM elements or HTML.

Provide exports for CommonJS

Provide exports for CommonJS when available.

Grab the global object by using "this" instead of passing "window" into the initialising function.

Make element creation & event registration pluggable, with a basic default implementation

jQuery is a bit heavy to be lugging about solely for the limited subset of its capabilities DOMBuilder needs.

Look at how it's being used and see if we could make those needs pluggable, with a basic default implementation which doesn't depend on a library, but will come with a caveat as to how comprehensively it attempts to deal with cross-browser issues.

license

I don't see a license in the README or package.json. Mind adding one?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.