Instance of template object and jQuery scope

I am reading a book and could not understand some code from it mentioned below.

"Another thing we should do is avoid global jQuery selectors such as $(’input[name=name]’).val(). The issue with this is that our template should only be able to manipulate elements inside of our template. If there happens to be another input[name=name] element on the page we might accidentally use that value instead of the one we were after.

To fix this we can change the scope of the jQuery call by using the second parameter of the event function - the parameter I named tpl, which stands for template and is an instance of the template object. It has a function called $, which reduces the scope of the jQuery selector down to just the template.

Hence we can update our code to:... 'submit form.create-team': function(e, tpl){ e.preventDefault(); var teamName = tpl.$('input[name=name]').val(); Teams.insert({name: teamName}); } ... "
I do not get this that tpl thing that how this is instance of template object and how they can used its as to reduce the scope ?

    **var teamName = tpl.$('input[name=name]').val();**

Multiple copies of templates can be rendered at the same time:

i.e. Two templates with the same name are rendered


They could both have buttons

<input type="button">

To keep track of which button has been clicked, (in an event map, for example) each template needs it’s own instance.

An instance is basically an individual copy.

The template object contains a lot of data about the template - you can see it with console.log(this) inside an Template.templateName.onRendered(function(){}) or inside similar functions

The jquery scope appears to be set using it’s domrange and a custom implementation to set the context for the HTML.$

Thanks a lot for explaining me so clearly.

1 Like