Any examples of modifying the state of a template?

The Meteor tutorials somehow manage to leave out a rather important example - adding and removing classes from an html element.

For example, with the built-in JQuery in Meteor:

Template.body.events({
  'click .tab' (event, instance) {
    const element = instance.$('.tab')
    element.addClass('is-active')
    // And the inverse:
    element.removeClass('is-active')
  }
})

Can someone please point me or provide me with an example that does this without using JQuery?

This is a quick hack to show the principle:

<template name="dynamicClasses">
<div class="tab" {{ someDynamicClasses }}">
  blah blah
</div>
Template.dynamicClasses.onCreated( function() {
  this.liveClasses = new ReactiveVar()
})

Template.dynamicClasses.events({
  'click .tab' (event, instance) {
    const state = instance.liveClasses.get()
    if (state === 'is-active') {
      instance.liveClasses.set('')
    } else {
      instance.liveClasses.set('is-active')
    }
  }
})

Template.dynamicClasses.helpers({
  someDynamicClasses() {
    return Template.instance().liveClasses.get()
  }
})

An important point is that for this to work in the case of multiple <div class="tab">, each of those div blocks should be templated.

<template name="outer">
  {{> dynamicClasses}}
  {{> dynamicClasses}}
  {{> dynamicClasses}}
  {{> dynamicClasses}}
</template>

That ensures each div gets its own, unique instance (and ReactiveVar). Clearly, you’d probably use a loop contruct to generate the inclusions dynamically, as well.

Hey Rob,

Sorry, but this did not work. It has the same error that pretty much all of the other tutorials and examples have: Cannot read property 'get' of undefined

In particular, it’s this line instance.liveClasses.get(). Even though we’re adding the liveClasses property during the onCreated() event, it’s not actually adding it or something.

Other examples I’ve seen use reactiveDict instead but the error is the exact same.

Are you using arrow functions by any chance? That would mean you get the wrong this binding and lose access to the newly created ReactiveVar

If you post your code up here we can take a look at why you might be having a problem

1 Like

Did you do meteor add reactive-var to your project?