Attached you find an example of client code: handling a jQuery simple slider which can changed its value by manual dragging or getting new values from server by message stream.
On Template.SLIDER.rendered event, I create the jQuery UI Slider on a Div element.
I save a reference var to the Div element in var Div_Slider
I did this, because I have to update the slider value also by event from server (here by stream notification)
I subscribed to the reactive Session var "slider_value" by Deps.autorun().
When Session.set is called, event should also update the Slider.value if this element was already rendered.
Instead using $('#servo-slide'). more than once and have to inspect the DOM again and again I prepared this local Div_Slider var as a reference and use it during interaction with the jQuery UI Slider.
Q: Is this the best and perfomant technic? - Creating local .js file scope vars to reference to commonly used elements?
Q: Do you have any suggestion to my sample code?
{ ... }
/*
--------------- Slider
*/
// save reference to slider
var Div_Slider = undefined;
// be reactive on Session value slider_value
Deps.autorun(function () {
// we just operate when available
if (Session.equals('slider_value', undefined))
return;
// be reactive on slider_value
var slider_value = Session.get('slider_value');
// set jQuery slider position
if (!_.isUndefined(Div_Slider)) {
Servo_Slider.slider({value: slider_value});
}
});
// listen to the stream
notifications.on('change_slider_value', function(new_value) {
// we are updating the sliders value, this will also update the Session value in onChange event
Session.set("slider_value", new_value);
});
Template.SLIDER.rendered = function () {
// save reference to elements
Div_Slider = $(this.find('#servo-slide'));
// update div as slider
Servo_Slider.slider({
min: 0,
max: 100,
step: 1,
range: "min",
value: Session.get("slider_value"),
change:
function(event, ui) {
// only do something if the event was generated here
if (event.originalEvent) {
// do your actions
}
}
});
}
{ ... }
Deps.autorunwhen the template is no longer in use. - nathan-m