connecting onDndDrop with dojo.dnd.Source - events

can any one tell me how to connect a dojo/dnd/Source object with onDndDrop event and its function

In case the link ever goes away or someone wants to use AMD, to connect the onDndDrop event to a dojo/dnd/Source, you can write the following:
require(["dojo/dnd/Source", "dojo/parser", "dojo/domReady!"], function(Source) {
var myDndSource = new Source("myDndSource");
myDndSource.on("DndDrop", function(source, nodes, copy, target) {
// Do something
});
});
For example:
require(["dojo/dnd/Source", "dojo/parser", "dojo/domReady!"], function(Source) {
var myDndSource = new Source("myDndSource");
myDndSource.on("DndDrop", function(source, nodes, copy, target) {
nodes.forEach(function(node) {
console.log("Dropped '" + node.innerText + "' on source '" + source.node.id + "'");
});
console.log("New order: " + source.getAllNodes().map(function(node) {
return node.innerText;
}).join(", "));
});
});
A full code example can be found here: http://jsfiddle.net/RFav3/

This tutorial contains everything you need to get started with dojo.dnd:
http://www.sitepen.com/blog/2008/06/10/dojo-drag-and-drop-1/

Related

AJAX dropdown list down not update with var string variable

I have a test script to update a county drop down list whenever the year or state is updated. When I used a literal string when year is selected, the county list updated fine. However when I tried to the county list using an ajax call and used a (var options) to build the list, the drop down list value changed to an empty list even though I verified the value of (var options) contains valid drop down list options.
Please help!
Thanks,
$('#State').on("change", function () {
var state = $('#State').val();
var year = $('#Year').val();
var obj = {
state: state,
year:year
};
alert("State changed:" + state + ":" + year);
AjaxCall('/RIC/GetCounties', JSON.stringify(obj), 'POST').done
(function (response) {
if (response) {
$('#DataId').html("<option value='test'>Test</option>");
var options = '';
options += "<option value='Select'>Select</option>\n";
for (i in response) {
options += "<option value='" + response[i].DataId + "'>" + response[i].County + "</option>\n";
}
$('#DataId').html("<option value='Select'>Select-S</option><option value='16'>Alameda-S</option>");
alert("Statitical Areas(S): " + options);
//$('#DataId').html(options); //This should work. How to get the value of options into the string
//$('#DataId').append(options);
}
}).fail(function (error) {
alert("County Error:" + error.StatusText);
});
});
$('#Year').on("change", function () {
var state = $('#State').val();
var year = $('#Year').val();
var obj = {
state: state,
year: year
};
alert("Year changed:" + state +":"+ year);
AjaxCall('/RIC/GetCounties', JSON.stringify(obj), 'POST').done
(function (response) {
if (response) {
$('#DataId').html("<option value='test'>Test</option>");
var options = '';
options += "<option value='Select'>Select</option>\n";
for (i in response) {
options += "<option value='" + response[i].DataId + "'>" + response[i].County + "</option>\n";
}
//$('#DataId').html("<option value='Select'>Select-Y</option><option value='16'>Alameda-Y</option>");
$('#DataId').html(options); //This should work. How to get the value of options into the string
alert("Statitical Areas(Y): " + options);
//$('#DataId').append(options);
}
}).fail(function (error) {
alert("County Error:" + error.StatusText);
});
});
});
function AjaxCall(url, data, type) {
  return  $.ajax({
     url:  url,
     type:  type  ?  type  :  'GET',
     data:  data,
     contentType:  'application/json'
   });
}  
Instead of using another function to call your $.ajax why not call it immediately. There’s no performance improvement on what you had done. Try to revert your code and just add async property if you want to wait the response before proceeding to your lower conditions.
I hope this will help you

This code is not run, getelementbyid return null

This code is not run, getelementbyid return null
<script type='text/javascript'>
CKEDITOR.on('instanceCreated', function (e) {
document.getElementById(e.editor.name + '_preview').innerHTML = e.editor.getData();
var a = $('#' + e.editor.name + '_preview').height();
$('#' + e.editor.name + '_txt').val(a.toString());
e.editor.on
('change'
, function (ev) {
document.getElementById(e.editor.name + '_preview').innerHTML = ev.editor.getData();
var a = $('#' + e.editor.name + '_preview').height();
$('#' + e.editor.name + '_txt').val(a.toString());
}
);
});
var config = { extraPlugins: 'onchange' };
CKEDITOR.replace('contents', config);
</script>
EDIT: Code should be understandable now.
Please see this link for instanceCreated. Although instance is created, it hasn't been initialized yet. If you want to work with the editor, please use the instanceReady event.
Please also make sure that element with id e.editor.name + '_preview' actually exists because another reason for your problem may be that such id doesn’t exist.

Does Hammer 2.0 allow me to to everything I do in 1.0.5?

My HTPC project (open source) uses Hammer 1.0.5 extensively - 32 separate hammer instances in many pages; 184 different event handlers; handles many different event types (tap, doubletap, touch, release, hold, drag, dragup, dragdown, swipeleft, swiperight, swipeup, swipedown). All the event handlers use delegation.
When I found I had a glitch on Safari on an iPad (every other touch is ignored), I came to look for anyone with the same problem and discovered I had missed the release of version 2. So ...
Is it wise to upgrade?
Can I do everything in version 2 that I could with version 1?
Is the upgrade fairly mechanical? (Set options to enable capability, use new names for events)?
I can't find any guidance for upgrading in the hammer documentation, which is a shame.
Thanks
Brian
Well the simple answer is that "No I can't easily port my Hammer 1.x implementation to 2.0".
Below is a snippet of one of my HTPC JS files, that adds actions to a <div> containing a EPG listing of TV programmes. This works very well with 1.x.
var listingsHammer = null;
function AddListingsHammerActions() {
$("#guideBrowserItems").each(function () {
var h = $(window).height() - 24
var t = $(this).offset().top
console.log("#guideBrowserItems h=" + h + "; t=" + t + " => " + (h - t))
$(this).height(h - t)
});
if (!listingsHammer) {
listingsHammer = $(".guideBrowserItems").hammer({ prevent_default: true });
}
EnableDragScroll(listingsHammer)
listingsHammer.on("tap", ".guideEpgProgramme", function (e) {
var programItem = this;
$(".guideEpgProgrammeDescription").remove();
$(".guideEpgProgrammeCancel").remove();
$(".guideEpgProgrammeRecord").remove();
$(".guideEpgProgrammeRecordSeries").remove();
$.ajax({
url: "/Guide/Description?id=" + programItem.id,
success: function (description) {
if (hasClass(programItem, "guideEpgProgrammeScheduled")) {
$(programItem).prepend('<img class="guideEpgProgrammeCancel" id="' + programItem.id + '" src="/Content/Buttons/SmallRound/Exit.png" />')
} else {
$(programItem).prepend('<img class="guideEpgProgrammeRecordSeries" id="' + programItem.id + '" src="/Content/Buttons/SmallRound/Transport.Rec.Series.png" />')
$(programItem).prepend('<img class="guideEpgProgrammeRecord" id="' + programItem.id + '" src="/Content/Buttons/SmallRound/Transport.Rec.png" />')
}
$(programItem).append('<div class="guideProgrammeInfo guideEpgProgrammeDescription">' + description + '</div>')
cache: false
}
})
});
listingsHammer.on("tap", ".guideEpgProgrammeRecord", function (e) {
var programItem = this;
$.ajax({
url: "/Guide/Record?id=" + programItem.id,
success: function (error) {
if (error == "") {
$(".guideSelectorItems").html("")
ReplacePane("guideBrowserItems", "/Guide/ListingsPane?mode=GuideSchedule", "none")
}
else {
alert(error)
}
cache: false
}
})
});
listingsHammer.on("tap", ".guideEpgProgrammeRecordSeries", function (e) {
var programItem = this;
$.ajax({
url: "/Guide/RecordSeries?id=" + programItem.id,
success: function (error) {
if (error == "") {
$(".guideSelectorItems").html("")
ReplacePane("guideBrowserItems", "/Guide/ListingsPane?mode=GuideSchedule", "none")
}
else {
alert(error)
}
cache: false
}
})
});
listingsHammer.on("tap", ".guideEpgProgrammeCancel", function (e) {
var programItem = this;
$.ajax({
url: "/Guide/Cancel?id=" + programItem.id,
success: function (error) {
if (error == "") {
$(".guideSelectorItems").html("")
ReplacePane("guideBrowserItems", "/Guide/ListingsPane?mode=GuideSchedule", "none")
}
else {
alert(error)
}
cache: false
}
})
});
listingsHammer.on("tap", ".guideEpgSeriesCancel", function (e) {
var seriesItem = this;
$.ajax({
url: "/Guide/CancelSeries?id=" + seriesItem.id,
success: function () {
$(".guideSelectorItems").html("")
ReplacePane("guideBrowserItems", "/Guide/ListingsPane?mode=GuideSeries", "none")
cache: false
}
})
});
}
There are a few things to note.
I only use one Hammer for the entire <div>, with delegation to each of the individual guideEpgProgramme sub-elements, so that when I touch a listed programme, the handler acts on that one sub-element.
This allows me to dynamically replace the contents of the <div> via Ajax (e.g. for another channel), with no need to re-register handlers.
The Record and Cancel button images are dynamically added and removed as needed and automatically gain the desired pre-registered actions.
The Hammer object is passed to a common utility function EnableDragScroll, which adds handlers for scrolling the (long, variable length) contents within the fixed size guideBrowserItems page area.
There are many instances of ReplacePane("guideBrowserItems", <NEW URL>) to dynamically alter the contents of the <div> without affecting the rest of the page or the script.
And this is just one of the 30+ different Hammer instance with corresponding handling.
None of this way of working appears to be possible in Hammer 2.0.
So for now I will stick with the old mechanisms.

Got promise not working

I'm trying to use promise to get in promise2
But if I have an object Widgets with several elements in it...
Why can't I have been able to get my console.log's output
Parse.Cloud.define("extract", function(request, response) {
var user = request.params.user;
var promise = Parse.Promise.as();
[...]
}).then(function() {
return query.find().then(function(results) {
_.each(results, function(result) {
[...]
Widget.objectId = result.id;
Widgets[timestamp] = Widget;
});
return promise;
}).then(function(results) {
for (var key in Widgets) {
var Widget = Widgets[key];
var widget_data = Widgets[key].widget_data;
var promise2 = Parse.Promise.as();
promise2 = promise2.then(function() {
return Parse.Cloud.run('extractWidgetData', {
'widget_data': widget_data,
}).then(function(newresult) {
Widgets[key].data = newresult.data;
console.log('--------WHY NOT HERE ALL TIME ?--------');
});
});
return promise2;
}
}).then(function() {
response.success(Widgets);
},
function(error) {
response.error("Error: " + error.code + " " + error.message);
});
});
});
I'm becoming crazy to run this damn Code
EDIT : I finally followed Roamer's advices to implement something but I'm not sure if it's the good way to work with Promise in series...
Parse.Cloud.define("extract", function(request, response) {
var user = request.params.user;
var Widgets = {};
...
... .then(function() {
return query.find().then(function(results) {
return Parse.Promise.when(results.map(function(result) {
var Widget = ...;//some transform of `result`
Widget.id = ...;//some transform of `result`
var timestamp = createdAtDate.getTime();
...
return Parse.Cloud.run('extractData', {
'widget_data': Widget.widget_data,
}).then(function(newresult) {
Widget.stat = newresult.stats;
return Widget;//<<<<<<< important! This ensures that results.map() returns an array of promises, each of which delivers a Widget objects.
});
}));
}).then(function() {
var promisedWidget = Array.prototype.slice.apply(arguments);
return Parse.Promise.when(promisedWidget.map(function(Widget) {
return Parse.Cloud.run('getWineStats', {
'id': Widget.data.id
}).then(function(stat) {
Widget.stat = stat;
return Widget;
});
}));
}).then(function() {
var promisedWidget = Array.prototype.slice.apply(arguments);
_.each(promisedWidget, function(Widget) {
var createdAtObject = Widget.createdAt;
var strDate = createdAtObject.toString();
var createdAtDate = new Date(strDate);
timestamp = createdAtDate.getTime();
Widgets[timestamp] = Widget;
});
return Widgets;
}).then(function(Widgets) {
response.success(Widgets);
},
function(error) {
response.error("Error: " + error.code + " " + error.message);
});
});
});
First, I echo Bergi's comment on indentation/matching parenthesis.
But ignoring that for a moment, at the heart of the code you have return query.find().then(...).then(...).then(...) but the flow from the first .then() to the second is incorrect. Besides which, only two .then()s are necessary as the code in the first then is synchronous, so can be merged with the second.
Delete the two lines above for (var key in Widgets) { then at least Widgets will be available to be processed further.
Going slightly further, you should be able to do all the required processing of results in a single loop. There seems to be little pont in building Widgets with _.each(...) then looping through the resulting object with for (var key in Widgets) {...}.
In the single loop, you probably want a Parse.Promise.when(results.map(...)) pattern, each turn of the map returning a promise of a Widget. This way, you are passing the required data down the promise chain rather than building a Widgets object in an outer scope.
Do all this and you will end up with something like this :
Parse.Cloud.define("extract", function(request, response) {
var user = request.params.user;
...
... .then(function() {
return query.find().then(function(results) {
return Parse.Promise.when(results.map(function(result) {
var Widget = ...;//some transform of `result`
...
return Parse.Cloud.run('extractWidgetData', {
'widget_data': Widget.widget_data,
}).then(function(newresult) {
Widget.data = newresult.data;
return Widget;//<<<<<<< important! This ensures that results.map() returns an array of promises, each of which delivers a Widget objects.
});
}));
}).then(function() {
//Here, compose the required Widgets array from this function's arguments
var Widgets = Array.prototype.slice.apply(arguments);//Yay, we got Widgets
response.success(Widgets);
}, function(error) {
response.error("Error: " + error.code + " " + error.message);
});
});
});

How can i define a variable in Json?

i want define a variable in Json callback.
Code;
$("select").change(function () {
var $variable = "";
$("select option:selected").each(function () {
$variable += $(this).text() + " ";
});
$("div.yaz").text($variable);
$('#result').html('loading...');
$.getJSON('program-bilgileri.php', function(JSON){
$('#result').empty();
$.each(JSON.$variable, function(i, program){
$('#result')
.append(program.isim +'<br />')
.append(program.bilgi+'<br />')
.append(program.adres+'<hr />');
});
});
})
.trigger('change');
program-bilgileri.php returns;
{
"programlar":[
{
"isim":"Zone Alarm",
"bilgi":"bilgisayarın güvenliğini sağlar",
"adres":"www.zonealarm.com"
},
{
"isim":"Opera",
"bilgi":"güvenli ve hızlı bir web tarayıcısıdır",
"adres":"www.opera.com"
},
{
"isim":"Photoshop",
"bilgi":"güçlü bir imaj işleme yazılımıdır",
"adres":"www.adobe.com"
}
]
}
The problem is here "$.each(JSON.$variable, function(i, program)" if I define $variable in JSON it isn't working.
Any idea?
The problems i see are
Inside the change event you are using $("select option:selected") which finds all select elements in the page, and not the changed one only.
use $(this).children('option:selected') instead.
I am assuming that you are allowing multiple selection on the select element and that is why you are doing += with the $variable.. (you are also adding a space at the end). That means, though, that the variable will be something like "programlar " or "programlar somethingelse".
Your returned JSON though has a key of programlar. A single word, no spaces.. so when you do JSON[$variable] which is the correct way to access an element based on the name in a variable, it does not match.
If the <select> element does not allow multiple selection then the solution is
$("select").change(function() {
var $variable = $(this).children("option:selected").text();
$("div.yaz").text( $variable );
$('#result').html('loading...');
$.getJSON('program-bilgileri.php', function(JSON) {
$('#result').empty();
$.each(JSON[$variable], function(i, program) {
$('#result')
.append(program.isim + '<br />')
.append(program.bilgi + '<br />')
.append(program.adres + '<hr />');
});
});
}).trigger('change');
If indeed it is a multiselect and each option can appear in the JSON then you must check for each option found in the variable.
$("select").change(function() {
var $variable = $(this).children("option:selected").map(function(){
return $(this).text();
}).get();
$("div.yaz").text( $variable.join(' ') );
$('#result').html('loading...');
$.getJSON('program-bilgileri.php', function(JSON) {
$('#result').empty();
for (index=0, length = $variable.length; index < length; index ++) {
$.each(JSON[$variable[index]], function(i, program) {
$('#result')
.append(program.isim + '<br />')
.append(program.bilgi + '<br />')
.append(program.adres + '<hr />');
});
}
});
}).trigger('change');
Try
$.each(JSON['programlar'], function(i, program) ... );
This will iterate over this part of your returned JSON object from PHP:
{
"isim":"Zone Alarm",
"bilgi":"bilgisayarın güvenliğini sağlar",
"adres":"www.zonealarm.com"
},
{
"isim":"Opera",
"bilgi":"güvenli ve hızlı bir web tarayıcısıdır",
"adres":"www.opera.com"
},
{
"isim":"Photoshop",
"bilgi":"güçlü bir imaj işleme yazılımıdır",
"adres":"www.adobe.com"
}

Resources