I'm using a simple template block helper that displays the a loading animation, hiding whatever is within it. This is very helpful for submitting forms and preventing the button from being pressed twice.
<template name="waiting">
{{#if isLoading}}
{{> loader}}
{{else}}
{{> UI.contentBlock}}
{{/if}}
</template>
I decided to put it in a block helper because I've never tried it before and I wanted to keep my code DRY -- I'm using this pattern in several places.
I'm running into issues using this block helper to access the Template.instance() not of the block helper but of the template it is within. I'm also running into problems with the template context. Here are the details of my problem:
I'm setting up a confirm-delete button like so:
{{#waiting isLoading=loadingDelete}}
{{#if confirmDelete}}
<button class="confirm">Are you sure?</button>
{{else}}
<button class="delete">Delete</button>
{{/if}}
{{/waiting}}
I'm also putting the loadingDelete and confirmDelete reactive variables in the template instance so I don't contaminate the Session:
Template.editRecord.created = ->
@loadingDelete = new ReactiveVar(false)
@confirmDelete = new ReactiveVar(false)
Template.editRecord.helpers
loadingDelete: () -> Template.instance().loadingDelete.get()
confirmDelete: () -> Template.instance().confirmDelete.get()
Then I create some events like this:
'click .delete': (e,t) -> t.confirm.set(true)
'click .confirm': (e,t) -> t.loadingDelete.set(true) _id = @_id Meteor.call 'deleteRecord', _id, (err) -> t.loadingDelete.set(false) if err console.log err else Router.go "home"
The problem with this implementation is that the Template.instance() refers to the waiting template in the confirmDelete helper here:
confirmDelete: () -> Template.instance().confirmDelete.get()
The second problem is that the data context in the event refers to the context of the waiting template and thus I need to use _id = Template.parentData()_id instead of _id = @_id. But I am not able to access the editRecord template instance or any of its variables from here which is frustrating.
I changed the template to this which fixes first problem.
{{#if confirmDelete}}
<button class="confirm">Are you sure?</button>
{{else}}
{{#waiting isLoading=loadingDelete}}
<button class="delete">Delete</button>
{{/waiting}}
{{/if}}
But this is ugly and not what I was intending. I was hoping just to replace my #if block with this block helper but I've ended up writing much more code while trying to be DRY with my templates. This just doesn't seem right.
I noticed that #if blocks don't cause these context and Template instance problems. Is there something I am missing?