Search code examples
javascriptmeteormeteor-blaze

Adding and removing Meteor templates


For a Meteor application I'd like the users to be able to add divs to a column by clicking on a button, with each of these having a button to remove the div. Here's an extract of the code:

<template name="MainTemplate">
    ....
    <a class="btn btn-sm" class="add-dynamic"></a>
    <div id="add-stuff-here"></div>
    ....
</template>

<template name="DynamicTemplate">
   <div id="dynamic-{{uniqid}}">
       <a class="btn btn-sm delete-dynamic" name="{{uniqid}}"></a>
   </div>
</template>

...and in the javascript file:

Template.MainTemplate.events({
    'click .add-dynamic'(event) {
     const random = String.fromCharCode(65 + Math.floor(Math.random() * 26));
     const uniqid = random + Date.now();
     Blaze.renderWithData(Template.DynamicTemplate, {uniqid: uniqid}, $("#add-stuff-here")[0])
    },
})

Template.DynamicTemplate.events({
    'click .delete-dynamic'(event){
        const target = event.target || event.srcElement;
        const id  = target.id;
        console.log("Button ID: " + id); // This is null
        new = $('#dynamic-' + id);
        new.parentNode.removeChild(new); // Therefore, this fails
    }
});

Adding the templates works as expected but deleting them fails as the id of the clicked button appears to be nil.

In any case I'm probably going about this in completely the wrong way (I haven't used Meteor for a long time and didn't know it very well anyway), and so would appreciate any suggestions as to how this might be accomplished.

ETA: The possible answer suggested in the comments includes:

UI.remove(self.view);

...which "expects a template rendered with Blaze.render". I'm not able to determine how to pass the identity of the template to be removed to the function which is run on the button click - does anyone have any suggestions?


Solution

  • In the end I worked around it by doing this:

    <template name="DynamicTemplate">
        <input type="text" class="dynamic-input" placeholder="Some text" />
    </template>
    
    Template.DynamicTemplate.events({
        'click .delete-dynamic'(event){
         inputs = $(".dynamic-input").length;
         if ( inputs > 1 ) {
            const element = $(".dynamic-input")[dynamic - 1];
            element.parentNode.removeChild(element);
            }
        }
    });
    

    That seems to do more-or-less what I was after and avoids the problem of the null ID which I mentioned in the original post.