I'm struggling to integrate a jquery-ui slider widget into my Meteor app. The idea is to have a slider value in a Mongo collection and the slider needs to be reactive (automatically synced between clients). I've achieved this and it works but the implementation is not very elegant and clean. It's quite hard to maintain, test and extend such code. I've achieved this via Tracker.autorun and jquery slider slide handle (_.throttle
is used to limit mongo update interval).
I'm new to Meteor, and it's awesome, but so far couldn't find better way to implement this (which I bet exists):
Slider = new Meteor.Collection("Slider");
if (Meteor.isClient) {
Template.slide.rendered = function() {
var handler = _.throttle(function(event, ui) {
var val = Slider.findOne({});
Slider.update({ _id: val._id }, {$set: {slide: ui.value}});
}, 50, { leading: false });
if (!this.$('#slider').data('uiSlider')) {
$("#slider").slider({
slide: handler
});
}
Tracker.autorun(function() {
var slider = Slider.findOne({});
if (slider) {
this.$('#slider').data('uiSlider').value(slider.slide);
}
});
};
}
//seed Collection
if (Meteor.isServer) {
if (Slider.find().count() == 0) {
Slider.insert({
slide: 20
});
}
}
HTML
<body>
<h1>jquery-ui slider test</h1>
{{> slide}}
</body>
<template name="slide">
<div id="slider"></div>
</template>