0

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?

asked Aug 30, 2021 at 5:51
2
  • Perhaps you can tell us WHY you want to do this - for now it sounds line an X/Y problem Commented Aug 30, 2021 at 5:54
  • I guess to keep it simple. If I can have a single function that handles all these cases, rather than three separate ones, wouldn't that be better? Commented Aug 30, 2021 at 5:56

1 Answer 1

1

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>

answered Aug 30, 2021 at 6:05
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.