Reputation: 6381
I am trying to convert a jQuery event to a Meteor event, so I can add a component to my Meteor project, without dropping into jQuery.
This is the code: https://github.com/IronSummitMedia/startbootstrap-simple-sidebar/blob/gh-pages/index.html#L91-L96
The original jQuery code:
<script>
$("#menu-toggle").click(function(e) {
e.preventDefault();
$("#wrapper").toggleClass("toggled");
});
</script>
My Meteor code:
Template.sidebar.events({
'click #menu-toggle': function(e) {
debugger;
e.preventDefault();
$("#wrapper").toggleClass("toggled");
}
});
Is this the correct way to convert a jQuery function into Meteor? Should this line be written differently to be more Meteor-like?
$("#wrapper").toggleClass("toggled");
Upvotes: 1
Views: 115
Reputation: 932
It is more code but a slightly cleaner, less jQueried version would be something like..
Template.sidebar.onCreated(function () {
this.showMenu = new ReactiveVar(false);
});
Template.sidebar.helpers({
showMenu: function () {
if (Template.instance().toggleClass.get()) {
return 'toggled';
}
}
});
Template.sidebar.events({
'click #toggle-menu': function (event, tmpl) {
tmpl.showMenu.set(tmpl.showMenu.get() ? false : true);
}
});
Then in the template:
<template name="sidebar">
<button type="button" id="toggle-menu">Show Menu</button>
<div class="menu {{showMenu}}">
<!-- toggled menu -->
</div>
</template>
Just to note it probably doesn't make much difference when you're replacing a quick jQuery call like $("#wrapper").toggleClass("toggled");
, but if you end up doing anything more complex with an event, you get into the realm of spaghetti code turning classes on and off with jQuery and maintaining consistent states. Best to have one 'source of authority' for whether the menu should be shown or hidden (IMO).
Upvotes: 1