Markdown previewer question

This is part of the code from the example project.

const renderer = new marked.Renderer();
renderer.link = function(href, title, text) {
  return `<a target="_blank" href="${href}">${text}` + '</a>';
};

I don’t understand this part of the code one bit.

First off I don’t understand what is ‘marked’ and why are we writing ‘new’ in front of it?

Then what does the ‘Renderer()’ function do?

And lastly why are we writing ‘renderer.link’ ?

I don’t understand this part of the code one bit.

Nothing?

First off I don’t understand what is ‘marked’ and why are we writing ‘new’ in front of it?

That must be because marked.renderer is a constructor.

Then what does the ‘Renderer()’ function do?

When I look in the source code, I see that this is a class. So that is a constructor - it sets up the object/class. By using this with the new keyword, we are creating a new instance of that class.

And lastly why are we writing ‘renderer.link’ ?

I don’t know this package, but since that class already has a property called “link” (line 136), we are overwriting that for this instance.

Again, I don’t know this package, but just looking at the JS, that is what I can see.

1 Like

That source code You found cleared things up a bit.

Inside of codepen it says that it’s used for this:

// INSERTS target="_blank" INTO HREF TAGS (required for codepen links)

I’m not sure what you mean by “inside of codepen”.

My apologies it was probably my mistake for not putting it this way:

// INSERTS target="_blank" INTO HREF TAGS (required for codepen links)
const renderer = new marked.Renderer();
renderer.link = function(href, title, text) {
  return `<a target="_blank" href="${href}">${text}` + '</a>';
};

This is the part of the code with it’s corresponding comment.

OK…

  1. Where is this coming from? What is the context?
  2. What is your question?

As to the comment, yeah, in code pen, you need to specify the target so it will open up a new window.

They copied it from the sample project
https://codepen.io/freeCodeCamp/pen/GrZVVO

1 Like

OK, that makes a little more sense.

The original marked module has a link method that returns a link. That link returned won’t work for codepen. So, they are overriding it with something that will work for codepen.

1 Like

Thank You, Sir
Now I finally get it.
Like I previously said that source code You managed to find was of great help.
So we are overwriting a link method to suit our needs.

Right, that link method works fine for most cases. So, we create an instance of the class and overwrite that specific method on our instance of that class.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.