I have developed a piece of code that is designed to transfer event handlers from one element to another while removing them from the previous control. You can see the functionality in action on this fiddle: http://jsfiddle.net/pydty4bq/
var slider = d3.select('#slider1');
var slider1Config = {
element: slider,
drag:function(e){
if(d3.event.toElement)
console.log('has toElement',d3.event.toElement.valueAsNumber);
else
console.log(d3.event.sourceEvent.srcElement.valueAsNumber);
},
dragstart:function(){console.log('dragstart!');},
dragend: function(){ console.log('dragend!');}
}
var _drag = new Drag(slider1Config);
_drag.element(d3.select('#slider2'));
The function _drag.element
is meant to transition event handlers from slider1 to slider2, but at the moment both elements are triggering event handlers.
//drag functionality
var Drag = (function(){
var _opts,
_drag = d3.behavior.drag();
var eventList = ['drag','dragstart','dragend'];
function attachEvents(opts){
eventList.forEach(function(e,i){
if(opts[e]){
_drag.on(e,this[e]);
}
else{
_drag.on(e,null);
}
}.bind(this));
};
function detachEvents(){
eventList.forEach(function(e,i){
if(_opts[e]){
_drag.on(e,null);
}
}.bind(this));
}
function Drag(opts){
_opts = opts;
attachEvents.call(this,opts);
_opts.element = opts.element.call(_drag);
_opts.element.attr('isDraggable',true);
}
Drag.prototype.drag = function(args){
_opts.drag(args);
};
Drag.prototype.dragstart = function(args){
_opts.dragstart(args);
}
Drag.prototype.dragend = function(args){
_opts.dragend(args);
}
Drag.prototype.element = function(el){
if(el){
detachEvents.call(this)
_opts.element = el;
attachEvents.call(this,_opts);
_opts.element.call(_drag);
}
}
Drag.prototype.config = function(opts){
_opts = opts;
attachEvents.call(this,_opts);
}
return Drag;
})();
There seems to be an issue with the detachEvents
function as it does not successfully remove event listeners from the previous element. What could be causing this problem?