Super Retarded Dog
Super Retarded Dog

Reputation: 87

Dynamic function call jquery

I have the following code:

function loadTemplate(templateName, templates, target){
        try {
            $("<div/>").load(path, function () {
                $(this).appendTo("body").unwrap();
                templates.map(template => {
                    if (template.hasOwnProperty("data")) {
                        $(target).after($.templates(template.name).render(template.data, utils)).hide().fadeIn(200)
                    } else {
                        $(target).after($.templates(template.name).render()).hide().fadeIn(200)
                    }
                })
            });
        } catch (error) {
            console.error(error);
        }
    
    }
}

It appends a list of templates using jsrender after a target element that has been provided. Now my question is, how can I modify this block of code so that I can use another function such as append() or prepend() dynamically without creating a separate function specifically for handling such scenarios? For example, instead of having separate functions for appending to a target element or prepending like this:

$(target).append($.templates(template.name).render(template.data, utils)).hide().fadeIn(200)

$(target).prepend($.templates(template.name).render(template.data, utils)).hide().fadeIn(200)

Would it be possible to just have a single function that handles them all, by somehow passing the operation to the function as a parameter?

Upvotes: 0

Views: 95

Answers (1)

mplungjan
mplungjan

Reputation: 177786

We can use bracket notation instead of the dot notation to access the jQuery method

const $tgt = $("#target")
$(".btn").on("click", function() {
  $tgt[this.dataset.action](`<span>Success</span>`)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn" data-action="before">
Before
</button>
<button class="btn" data-action="after">
After
</button>
<button class="btn" data-action="prepend">
Prepend
</button>
<button class="btn" data-action="append">
Append
</button>
<div id="container">
  <span id="target"><hr/></span>
</div>

Upvotes: 1

Related Questions