Question

I want to port domjs for browser.

var mytemplate = function () {
  header(
    h1('Heading'),
    h2('Subheading'));

  nav(
    ul({ 'class': 'breadcrumbs' },
      li(a({ href: '/' }, 'Home')),
      li(a({ href: '/section/'}, 'Section')),
      li(a('Subject'))));

  article(
    p('Lorem ipsum...'));

  footer('Footer stuff');
};

But I don't know how to attach some methods like 'header' 'h1' 'h2' to 'mytemplate'.

How can I use header() without 'this' keyword.


Failed Case:

   template.apply($funcs),
   template.bind($funcs)(),
   template.call($funcs),

I can't use header(), in template. (In this case, 'this.header' was available)


Was it helpful?

Solution

First you should check the documentation:

var domjs = require('domjs/lib/html5')(document);
// Execute mytemplate with h1, h2 etc. functions attached
var mydom = domjs.build(mytemplate);
console.log(mydom.firstChild.nodeName); // header

If you're asking how does it work (?) as you have some custom handling in mind - It works by polluting the global scope for the time of function being called. You can see how it's done here -> https://github.com/medikoo/domjs/blob/v0.2.3/lib/dscope.js#L32-L36

btw. at all times you can access all those functions on domjs.map as domjs.map.header, domjs.map.h1 etc.

Method of using global scope, is controversial and has it's downsides (e.g. functions are not available after function returns) and in upcoming version of domjs this method would no longer be used. As an alternative Webmake (and possibly Browserify) plugins would be provided, so domjs templates can be bundled with those functions assured in local scope, then things will work natural way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top