简体   繁体   中英

How to call a method from a dynamic template in Meteor

I'm building a settings page in Meteor which will include dynamic templates for the many categories of settings.

What I'm trying to do is have a method in my category template that will be called when I click the submit button on the parent template.

settings.html

<div>
  {{> Template.dynamic template=settings}}
  <div class="submit">
    <button>Save Changes</button>
  </div>
</div>

settings.coffee

Template.settings.events
    'click .submit button': ->
        dynamiclyLoadedTemplate.save()

my-dynamic-template.coffee

Template.dynamicTemplate.onCreated ->
    @save = ->
        # doSomething()

my-other-dynamic-template.coffee

Template.otherDynamicTemplate.onCreated ->
    @save = ->
        # doSomethingElse()

Is this possible?

Should I create these methods as window methods, instead of template methods?

You can add the following code in your child template:

Template.childTemplate.onCreated ->

    settingsTemplate = this.parentTemplate(...) # ... = number of upstream levels
    settingsTemplate.child ?= []
    settingsTemplate.child.push this

    @save = ->
        console.log 'Save called'

So you can call the following code on the parent template:

Template.parentTemplate.events

    'click .submit button': ->
        console.log 'submit button clicked'

        instance = Template.instance()

        if instance.child?.length > 0
            for child in instance.child
                child.save?()

I have a similar pattern where I just attach the events to the parent template (the one that loads the dynamic template). The data context will be that of the parent but that's still better than attaching the methods to the window object especially since in my case the sub-templates all deal with the same type of object anyway.

In your case, first make the parent of your dynamic templates a template itself:

<template name="parent">
  <div>
    {{> Template.dynamic template=settings}}
    <div class="submit">
      <button>Save Changes</button>
    </div>
  </div>
</template>

Then just attach the event(s) to that parent:

Template.parent.events
    'click .submit button': ->
        save() // generic save function you've defined, for example in this file

This works well when the dynamically included templates have the same kind of object and usually similar DOM elements, at least those that you want to attach events to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM