Possible to set event.dataTransfer asynchronously after drag start? - javascript

Currently I am working on a scenario that I need to change the data attached to a dragging element after the dragging starts. Basically the drop zones are input fields or textareas so i would like to use the native event.dataTransfer.setData since the native drag-drop can make the caret move with mouse.
Everything works perfectly at the beginning if i just call the setData() synchronously in the listener of dragstart event.
dragItem.addEventListener("dragstart",function(event){
event.dataTransfer.setData("text/plain","data set in dragstart");
})
However, my scenario could be that the data is from an asynchronouly callback function like an AJAX request. Then I attempted to call setData() in this callback function but nothing seems to be successfully set.
dragItem.addEventListener("dragstart",function(event){
event.dataTransfer.setData("text/plain","data set in dragstart");
//like a callback in Ajax or resolve function of a promise.
setTimeout(function(){
console.log("attempt to set data asynchonrously after drag start");
event.dataTransfer.setData("text/plain","asynchonrously set data");
//looks like failed, the console output is empty, even not the original set one
console.log(event.dataTransfer.getData("text/plain"));
},200)
})
I also tried to change the data in dragenter and even drop event listeners of the drop zones. But there was still no luck.
This plunker shows what i have tried.
Then i referred to the MDN API document to find offical api description of the dataTransfer object. But there is nothing about problems like asynchronously using setData after drag start. One really weird thing is that if i try to compare the two dataTransfer references in dragstart and drop event, the are NOT the same object. Now I have no clue what is actually happening.
So my questions are
Is it possible to set the data in dataTransfer after the dragging is started with the native APIs (without using event.preventDefault) ?
If the first question's answer is NO, what kind of workaround could I try? I could think of something about how to save and get the data to transfer. My main concern is that if event.preventDefault() is used on drop, it is not easy to get the caret move with mouse like the native dropping does.

Here is your answer.
Firstly,You can only set data in your dragstart event. So, every time any dragstart event starts it sets value and what ever you set asynchronouly will not get reflected no matter what.
So, one thing that you can do is have a global object and set that on drag start event like this:
var someObj = {
asd : 'something'
}
and set in you dragstart callback, like this:
dragItem.addEventListener("dragstart",function(event){
event.dataTransfer.setData("text/plain", someObj.asd);
dataTransferObject = event.dataTransfer;
setTimeout(function(){
console.log("attempt to set data asynchonrously after drag start");
//event.dataTransfer.setData("text/plain","asynchonrously set data");
someObj.asd = 'asynchonrously';
//looks like failed, the console output is empty
console.log(event.dataTransfer.getData("text/plain"));
}, 100)
})
Object is by default reference type.
Now, You can set someObj.asd to any value you want and you will see new value reflected. But there is a problem with this approach, value will be reflected after drop happens means after event has been ended.
So, to solve your problem what you can do is don't set any value on dragstart just set some value to someObj.asd on drag start and use someObj.asd on drop.
Here is a link of what i'm trying to explain:
https://plnkr.co/edit/SZhI9lGRI37eEd1nWfhn?p=preview
see console on drop event you will see reflected value there.
DON'T SEE UI JUST GO FOR CONSOLE

Related

View source function for onChange field event in Dynamics CRM

The onChange event for a field on my opportunity form is being called twice and I'm trying to track down the source of the second call. I've already passed the execution context into the onChange function but don't know any way to see the source of the call from there. Now I'm wondering if there's a way to see the pending events for an XRM page, does anyone know where that information is?
My code is basically this, tied to onLoad of the opportunity form. There could be a plugin or 3rd party library or something updating the field, but nothing jumps out.
function onLoad() {
Xrm.Page.data.process.addOnStageChange(handleStageChange);
}
function handleStageChange() {
var dateFieldName = "new_enteredstage1"
var dateFieldAttr = Xrm.Page.getAttribute(dateFieldName);
if (dateFieldAttr) {
dateFieldAttr.setValue(new Date());
}
}
If new_enteredstage1 is null when the stage change occurs then 2 calls occur and the value is set and immediately reset to null. If new_enteredstage1 has a value the value is updated as expected. Again, there could be some third party code that I'm missing but I have no idea how to track it down.
UPDATE:
This only happens on date fields, and it happens on all date fields. If I replace the code with a number field the value is not reset to null.
There's a know issue (example) related to the "new" form rendering engine (Turbo Forms) that can cause this issue.
You can try using the legacy form rendering engine and see if it solves the problem:

Ignite UI IgCurrencyEditor

I am trying to programmatically update a currency field to run the value changed event which holds a numeric calculation. I want the value to set to zero using something like.
$('.tester').igCurrencyEditor("setFocus");
$('.tester').igCurrencyEditor('option','value', 0);
Then when I blur out, or not sure what to do here, the valueChanged event should trigger as per the API docs (It can be raised on lost focus or on spin events).
But I can't seem to trigger the value changed event, it only works when I manually click into the input and change the number.
The valueChanging and valueChanged events would trigger when a user interaction changes the displayInput value of the editor, and the corresponding valueInput value is different from the display input one. The editors have adopted the same approach as all other Ignite UI controls where events do not trigger on API calls, because when an API call is performed, the developer can choose whether to invoke their event handler after the API call, or not.
There's two things that you can do to invoke your event handler. First one is to cache the event handler method and invoke it manually:
$('.tester').igCurrencyEditor({
...
valueChanged: valueChanged,
...
});
function valueChanged(event, ui) {
// event handler
};
$('.tester').igCurrencyEditor("setFocus");
$('.tester').igCurrencyEditor('option','value', 0);
valueChanged(null, { /* if you need arguments */ });
The second one is to extend the currency editor and override the method that performs the check whether these events should be triggered, and make it always trigger the events:
$.widget("ui.igCurrencyEditorExtension", $.ui.igCurrencyEditor, {
_processValueChanging: function (value) {
this._triggerInternalValueChange(value);
}
}
The second approach requires you to switch to using the igCurrencyEditorExtension and may cause side effects, as the method performs other checks as well.
Anyways, what Alex Marinov has suggested should work, but it depends on your editor configuration, depending on whether you've set nullValue, allow null values in the editor, etc.
you need a function like this:
function clearValue() {
$('.tester').igCurrencyEditor('option','value', "");
$('.tester').igCurrencyEditor('field').blur();
}
The result will be that the displayed value inside the currency editor is "$0.00" and the valueChanged event is fired.

waiting till an on change handler is complete before saving model

I have a User model(Backbone.js) and I want to update its settings attribute and then save it to the server. Settings is in JSON format, and the way I have it set up is that settings is the string version and settingsJSON is the object version. I bind functions to the change event of each so that when one changes, it updates the other.
The problem I am having, is that the save method is running before the changed handler is finished running. Is there any way i could ensure that all event handlers for that model are complete or something like that?
how I'm calling it:
currentUser.get('settingsJSON').apps = appsEnabled;
currentUser.save();
My event handlers:
Initialize: function() {
var that = this;
this.on("change:settingsJSON", function(model){
model.set({settings: JSON.stringify(model.get('settingsJSON'))});
});
this.on("change:settings", function(model){
model.set({settingsJSON: JSON.parse(model.get('settings'))});
});
}
#fencliff:
The change event is firing when I run this and works properly, I had it print the new settings string to the console.
Are you sure that they are called synchronously? I added console.log('changed') to the end of the .on(change) and put console.log('saved') directly after currentUser.save() and every time the console read:
saved
changed
For now I have just made it so that I stringily the JSON and save it to settings directly before I save and that works fine.
Backbone events are executed synchronously. That means that unless you (or some library) has overridden some part of the event handling, the change handlers will have processed as soon as you execute the next line of code.
In you code example there is another problem. When you call
user.get('settingsJSON').apps = appsEnabled;
The change event will not fire, because the value of settingsJSON has not been changed, merely the contents of the object were modified. The model.attributes.settingsJSON is still the same object as before.
The events are fired only when you call set on the property, and the new value is a different object. For example:
user.set('settingsJSON', _.extend({}, user.get('settingsJSON'), {apps:appsEnabled});
Another problem, it would seem, is that your event handlers, if triggered, would cause the change event being fired twice for the property which was first set:
this.on("change:settingsJSON", function(model){
//-> changes settings, and set triggers change
model.set({settings: JSON.stringify(model.get('settingsJSON'))});
});
this.on("change:settings", function(model){
//-> changes settingsJSON, and set triggers change
model.set({settingsJSON: JSON.parse(model.get('settings'))});
});
To solve that issue, call set with {silent:true} or modify the model.attributes hash directly.
Edited with corrections by #muistooshort.
Edited again with further corrections

HTML5 DnD dataTransfer setData or getData not working in every browser except Firefox

Consider this JSFiddle. It works fine in Firefox (14.0.1), but fails in Chrome (21.0.1180.75), Safari (?) and Opera(12.01?) on both Windows (7) and OS X (10.8). As far as I can tell the issue is with either the setData() or getData() methods on the dataTransfer object. Here's the relevant code from the JSFiddle.
var dragStartHandler = function (e) {
e.originalEvent.dataTransfer.effectAllowed = "move";
e.originalEvent.dataTransfer.setData("text/plain", this.id);
};
var dragEnterHandler = function (e) {
// dataTransferValue is a global variable declared higher up.
// No, I don't want to hear about why global variables are evil,
// that's not my issue.
dataTransferValue = e.originalEvent.dataTransfer.getData("text/plain");
console.log(dataTransferValue);
};
As far as I can tell this should work perfectly fine and if you look at the console while dragging an item you will see the id written out, which means that it's finding the element just fine and grabbing it's id attribute. The question is, is it just not setting the data or not getting the data?
I'd appreciate suggestions because after a week of working on this with three attempts and some 200+ versions, I'm starting to loose my mind. All I know is it used to work back in version 60 or so and that specific code hasn't changed at all...
Actually, one of the major differences between 6X and 124 is that I changed the event binding from live() to on(). I don't think that's the issue, but I've come to see a couple failures from Chrome when it comes to DnD while working on this. This has been debunked. The event binding method has no effect on the issue.
UPDATE
I've created a new JSFiddle that strips out absolutely everything and just leaves the event binding and handlers. I tested it with jQuery 1.7.2 and 1.8 with both on() and live(). The issue persisted so I dropped down a level and removed all frameworks and used pure JavaScript. The issue still persisted, so based on my testing it's not my code that's failing. Instead it appears that Chrome, Safari and Opera are all implementing either setData() or getData() off spec or just failing for some reason or another. Please correct me if I'm wrong.
Anyway, if you take a look at the new JSFiddle you should be able to replicate the issue, just look at the console when you're dragging over an element designated to accept a drop. I've gone ahead and opened a ticket with Chromium. In the end I may still be doing something wrong, but I simply don't know how else to do DnD at this point. The new JSFiddle is as stripped down as it can get...
Ok, so after a bit more digging around, I found that the problem actually isn't with Chrome, Safari, and Opera. What gave it away was that Firefox was supporting it and I just couldn't say the other browsers are failing, since that's something I'd normally accept for IE.
The real cause of the issue is the DnD specification itself. According to the spec for the drag, dragenter, dragleave, dragover and dragend events the drag data store mode is protected mode. What is protected mode you ask? It is:
For all other events. The formats and kinds in the drag data store
list of items representing dragged data can be enumerated, but the
data itself is unavailable and no new data can be added.
That translates to, "you have no access to the data that you set, not even in read only mode! Go f#&# yourself.". Really? Who'se the genius that came up with this?
Now, to get around that limitation you have few choices, and I'm only going to outline two that I've come up with. Your first one is to use an evil global variable and pollute the global namespace. Your second choice is to use the HTML5 localStorage API to perform the EXACT same functionality that the DnD API should have provided to begin with!
If you go down this route, which I have, you're now implementing two HTML5 APIs not because you want to, but because you have to. Now I'm starting to appreciate PPK's rant about the disaster that the HTML5 DnD API is.
The bottom line is this, the spec needs to be changed to allow for access to the stored data even if it's only in read only mode. In my case, with this JSFiddle, I'm actually using the dragenter as a way to look ahead at the drop zone and verify that I should allow a drop to occur or not.
In this case Mozilla apparently opted out of full compliance with the spec which is why my JSFiddle was working just fine in it. It just so happens that this is the one time I fully support not supporting the full specification.
There is a reason for the "protected" bit....drag/drop can span completely different windows, and they didn't want somebody to be able to implement a "listener" DIV that would eavesdrop on the content of everything that was dragged over it (and maybe send those contents by AJAX to some spy server in Elbonia). Only the DROP area (which is more clearly under the user's control) gets the full scoop.
Annoying, but I can see why it might be considered necessary.
var dragStartHandler = function (e) {
e.originalEvent.dataTransfer.effectAllowed = "move";
e.originalEvent.dataTransfer.setData("text/plain", this.id);
};
The problem is with the "text/plain". The standard specification in MSDN documentation for setData is just "text" (without the /plain). Chrome accepts the /plain, but IE does not, in any version I tried.
I struggled with the same problem for several weeks, trying to figure out why my "drop" events weren't firing properly in IE while they did in CHrome. It was because the dataTransfer data hadn't been properly loaded.
I know you already answered this, but this is a useful thread -- I just wanted to add an addendum here -- if you're setting the data yourself, you can always add the data into the field itself (ugly I know), but it prevents having to re-create functionality:
For instance, if setting your own custom data:
dataTransfer.setData('mycustom/whatever', 'data');
append the data as a new data entry, and iterate:
dataTransfer.setData('mycustom/whatever/data/{a json encoded string even}');
querying:
// naive webkit only look at the datatransfer.types
if (dataTransfer.types.indexOf('mycustom/whatever') >= 0) {
var dataTest = 'mycustom/whatever/data/';
// loop through types and create a map
for (var i in types) {
if (types[i].substr(0, dataTest.length) == dataTest) {
// shows:
// {a json encoded string even}
console.log('data:', types[i].substr(dataTest.length));
return; // your custom handler
}
}
}
tested in chrome only
Something also worth noting is that if you leave the execution chain using a timeout, the dataTransfer object won't have your data anymore.
e.g.
function dropEventHandler(event){
var dt = event.dataTransfer.getData("text/plain"); // works
var myEvent = event;
setTimeout(function(){
var dt = myEvent.dataTranfer.getData("text/plain"); // null
}, 1);
}
I was getting same error for below code:
event.originalEvent.dataTransfer.setData("text/plain",
event.target.getAttribute('id'));
I Changed code to:
event.originalEvent.dataTransfer.effectAllowed = "move";
event.originalEvent.dataTransfer.setData("text", event.target.getAttribute('id'));
And it worked for me.
I came across this post because I was having a similar experience with Chrome's dataTransfer.setData() and dataTransfer.getData() functions.
I had code that looked something like this:
HTML:
<div ondragstart="drag(event)" ondrop="newDrop(event)"></div>
JAVASCRIPT:
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function newDrop(ev){
var itemDragged = ev.dataTransfer.getData("text");
var toDropTo = ev.target.id;
}
The code worked perfectly fine in Internet Explorer but when it was tested in Chrome, I was unable to get values set in my dataTransfer object (set in drag function) using the dataTransfer.getData() function in the newDrop function. I was also unable to get the id value from the statement ev.target.id.
After some digging around on the web, I discovered that I was suppose to use the event parameters currentTarget property rather than the events target property. Updated code looked something like this:
JAVASCRIPT:
function drag(ev) {
ev.dataTransfer.setData("text", ev.currentTarget.id);
}
function newDrop(ev){
var itemDragged = ev.dataTransfer.getData("text");
var toDropTo = ev.currentTarget.id;
}
With this change I was able to use the dataTransfer.setData() and dataTransfer.getData() functions in chrome as well as internet explorer. I have not tested anywhere else and I am not sure why this worked. Hope this helps and hopefully someone can give an explanation.
I was working on a website testing with Firefox.
In WAMP on my laptop, code like the OP's worked. However, when I moved the website to HOSTMONSTER, it didn't work there.
I followed Joshua Espana's answer, and it resolved my problem.
failed:
ev.dataTransfer.setData("text/plain", ev.target.id);
worked:
ev.dataTransfer.setData("text", ev.currentTarget.id);
Thank, Joshua!
Anything pased to the dataTransfer only becomes available on ondrop events but ONLY on ondrop events (I believe this is a security consideration to prevent data being exposed to nefarious elements during a drag).
If you try adding an ondrop handler you should see the data exposed. Well at least you would if there weren't for one final trick...
To get the drop event to fire you need call .preventDefault on the dragover event or it prevents the drop event from firing
HTML (Angular)
<div (dragstart)="handleDragStart($event)"
(dragover)="handleDragover($event)"
(dragend)="handleDragEnd($event)"
(drop)="handleDrop($event)">
<div class="sortItem">item 1</div>
<div class="sortItem">item 2</div>
<div class="sortItem" draggable="true">Draggable</div>
<div class="sortItem">item 4</div>
</div>
Handlers (Typescript)
handleDragStart(event: DragEvent){
event.dataTransfer?.setData("text", '{"some": "data"}')
console.log('dragstart data:', event.dataTransfer?.getData("text"))
}
handleDragover(event: DragEvent) {
console.log('dragover data:', event.dataTransfer?.getData("text") || 'none')
event.preventDefault()
}
handleDragEnd(event: DragEvent) {
console.log('drag end data:', event.dataTransfer?.getData("text") || 'none')
}
handleDrop(event: DragEvent) {
console.log('drag drop data:', event.dataTransfer?.getData("text") || 'none')
}
Output from the above
If you drop the item INSIDE the container with the ondrop handler
If you don't cancel the dragover event...
If you drop the item OUTSIDE container with the ondrop handler
If you don't cancel the dragover event...
Other relevant SO questions
SO: Data only available on drop
SO: Drop event not firing
I also faced with this problem but no way worked for me when I set the data in ondrag function and get it back it gives the data but when try in other events like dragover and drop it dose not work.
I went this way maybe its not a proper answer but may help some one
let selectedId = 0;
function onDrag(params) {
// event.dataTransfer.setData("text",params);
selectedId = params
}
function onDragOver(params) {
// event.preventDefault()
// const data = event.dataTransfer.getData("text");
let id = selectedId
}

Preventing form submission with Dojo

I have a Dojo SubmitButton with jsId="saveParamButtonWidget". I overrided its onClick method by putting:
saveParamButtonWidget.onClick = editParam
I defined the editParam() function like this:
function editParam(eventObj) {
dojo.stopEvent(eventObj);
// ...
}
dojo.stopEvent() is supposed to stop event bubbling and default processing. However, the browser will submit the form anyway. I also tried with the following:
function editParam(eventObj) {
eventObj.stopPropagation();
eventObj.preventDefault();
// ...
}
Same thing. The only way I've managed to prevent form submission is by returning "false" from the event handler:
function editParam(eventObj) {
// ...
return false;
}
Can someone tell me why the first two ways did not work? Thanks.
Okay, after doing some digging through the source, I believe I can answer your question definitively.
The reason dojo.stopEvent() doesn't work, but return false does, is entirely due to how dijit.form.Button is coded. If you're interested, it's time for a little field trip. Keep your hard hats on.
When a dijit.form.Button is clicked...
The button's _onButtonClick method is invoked. (This is hooked up in the template, to the special ondijitclick event which captures not only mouse click but also certain keypresses, for a11y purposes.)
The _onButtonClick method first invokes the _onClick method, which, presuming the button is not disabled (which it's not in this case), invokes and returns the result of the onClick method. This is of particular interest since it's the method you're overriding!
Coming back to _onButtonClick, if _onClick returned precisely false (e.g. if your onClick handler returned false), _onButtonClick immediately bails out. This is why returning false makes your code work as desired. But what happens if it doesn't bail out there? Let's follow the trail further...
Next, _onButtonClick checks whether this button not a descendant of an actual HTML form, but is a descendant of a widget with an _onSubmit method (duck-typing). I'm assuming that in your case it is inside a real form (dijit.form.Form counts), so we'll skip over this. (I am under the impression that this code path wouldn't actually end up submitting, whereas yours apparently does.)
One final condition is checked: if the button has a valueNode defined (it does), the click method of this node is invoked. Unfortunately, this produces an entirely new event object on an invisible input type="submit" node under your form, and thus anything you tried to tell the original event is rendered immaterial, and the form goes on to submit! This is why dojo.stopEvent did not work - this code in dijit.form.Button pays it absolutely no heed.
I cooked this up as a somewhat-limited proof of concept (be sure to open firebug/etc. to get the logs): http://jsfiddle.net/Bf5H8/
Perhaps this is something that should be logged as a bug, but I suppose the initial thought may have been that supporting the well-known return false mechanism would be enough.
All this being said, it's quite possible that overriding onSubmit of the form is more in-line with your interests than overriding the button's onClick anyway (as S.Jones suggested), but at least this should solve the mystery.
Interesting question. +1
I believe you have to use dojo.connect to connect your function to a DOM event to get access to those methods with an event object.
See: The Event Object (DojoTollkit.org Reference Guide)
The Event Object
When you connect a function to a DOM
event with dojo.connect,
Dojo passes your function a normalized
event object. This means that,
regardless of the client's browser,
you can count on a set of standard
attributes about the event and a set
of methods to manipulate the event.
Assume that your function has been
called by dojo.connect and takes an
argument named event, like:
dojo.connect(dojo.byId("node"), "onclick", function(event){
// the var 'event' is available, and is the normalized object
});
...
Dojo normalizes the following methods with an event object:
event.preventDefault — prevent an event's default behavior (e.g., a link from loading a new page)
event.stopPropagation — prevent an event from triggering a parent node's event
Additionally, dojo.stopEvent(event)
will prevent both default behavior any
any propagation (bubbling) of an
event.
That said, placing a function like the one below in your form to perform some logic before submitting it, is a fairly clean, easily understood & maintainable approach.
<script type="dojo/method" event="onSubmit">
if (!this.validate()) { // or whatever else you'd like to evaluate
// insert calls here...
return false;
}
return true;
<script>
Cheers.
I had the same issue for using dojo.stopEvent
This issue is solved the form submission issue like this - here it is a simple form used to connect through dojo:
this.formId = dojo.byId("formId");
dojo.connect(this.formId, 'onsubmit', function(evt) {
var val_main = validate_this_form(0);
if(val_main == false)
dojo.stopEvent(evt);
});

Categories