Colton45
Colton45

Reputation: 270

Meteor proper constant use

I'm utilizing a package for WYSIWYG (bootstrap3-wysiwyg5) on a text area. The package is working as intended but the menu to modify text with bold, italics, etc. is multiplying whenever the page is rendered.

Here's what it looks like

I thought using the {{#constant}} block would stop this but it doesn't appear to be doing anything.

So, two questions:

  1. Am I using the {{#constant}} block incorrectly in this instance?
  2. If not, any recommendations on stopping a rerender situation like this?

Code below:

To use the wysiwyg editor you simply add it to whatever textarea you want to use. In the client I have:

Template.announcements.rendered = function(){
  $('#announcement_message').wysihtml5({
    "font-styles": false, //Font styling, e.g. h1, h2, etc. Default true
    "emphasis": true, //Italics, bold, etc. Default true
    "lists": true, //(Un)ordered lists, e.g. Bullets, Numbers. Default true
    "html": false, //Button which allows you to edit the generated HTML. Default false
    "link": true, //Button to insert a link. Default true
    "image": false, //Button to insert an image. Default true,
    "color": false //Button to change color of font
  });;
};

Then in the template I have:

{{#constant}}
  <textarea id="announcement_message" class="form-control" name="message" type="text"></textarea>
{{/constant}}

Upvotes: 2

Views: 921

Answers (1)

nickell
nickell

Reputation: 389

A constant block typically works that way, but your problem lies with how many times that rendered function is actually being run. If you put a console.log() in your Template.announcements.rendered(), I'd be willing to bet that it would show up 4 times.

This won't be a problem in Meteor's new rendering system called Blaze. They're addressing this very issue here.

Ben McMahen has a great post about Meteor's rendered callback and in that, he had a suggested code block for making sure something runs only once, and it's by attaching a rendered property to the Template instance like so:

Template.announcements.rendered({
   if(!this.rendered) {
      // This code only runs once
      $('#announcement_message').wysihtml5({
         "font-styles": false, //Font styling, e.g. h1, h2, etc. Default true
         "emphasis": true, //Italics, bold, etc. Default true
         "lists": true, //(Un)ordered lists, e.g. Bullets, Numbers. Default true
         "html": false, //Button which allows you to edit the generated HTML. Default false
         "link": true, //Button to insert a link. Default true
         "image": false, //Button to insert an image. Default true,
         "color": false //Button to change color of font
      });;
      this.rendered = true;
   }
});

Upvotes: 1

Related Questions