Paul
Paul

Reputation: 209

Return Function Arguments from another Function

I am trying to streamline some code but am hitting errors when I am converting something to a function. I am effectively trying to create one function that takes a single input, and then returns three things that end up as three arguments for another function.

Note: the final function that will take three arguments is a method titled md.use()

The original (working) code is as follows:

md.use(require('markdown-it-container'), 'warning', {

  render: function (tokens, idx) {
    var m = tokens[idx].info;
    if (tokens[idx].nesting === 1) {
      return '<aside class="warning">' + md.utils.escapeHtml(m[0]);
    } else {
      return '</aside>\n';
    }
  }
});

My attempt at streamlining it / making it reusable is:

function aside(name) {
  return [require('markdown-it-container'), name, {

    render: function (tokens, idx) {
      var m = tokens[idx].info;
      if (tokens[idx].nesting === 1) {
        return '<aside class="' + name + '">' + md.utils.escapeHtml(m[0]);
      } else {
        return '</aside>\n';
      }
    }
  }]
}

md.use.apply(null, aside('warning'));

This creates the following error when I try to build:

TypeError: Cannot read property 'block' of null
    at Function.container_plugin (/Users/Paul/Development/shins/node_modules/markdown-it-container/index.js:138:6)
    at MarkdownIt.use (/Users/Paul/Development/shins/node_modules/markdown-it/lib/index.js:496:10)

Upvotes: 1

Views: 54

Answers (1)

haim770
haim770

Reputation: 49095

In your first attempt, the call to use() is direct through the md instance, hence invoked in the context of md (this === md).

In your second attempt, you're using md.use.apply(null) that's invoking use() without its original context (which is the md instance).

Try this instead:

md.use.apply(md, aside('warning'));

See MDN

Upvotes: 1

Related Questions