Constrain position of Dojo FloatingPane - dojo

I have a dojox.layout.FloatingPane (as a custom dijit) which can be positioned anywhere within its enclosing div. My problem is that the user can potentially drag the FloatingPane completely outside of its container and be unable to retrieve it. Is there any easy way to force the FloatingPane to remain entirely visible at all times?
Here's my code:
dojo.provide("ne.trim.dijits.SearchDialog");
dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.require("dojox.layout.FloatingPane");
dojo.declare("ne.trim.dijits.SearchDialog", [dijit._Widget, dijit._Templated], {
templateString: dojo.cache("ne.trim.dijits", "templates/SearchDialog.html"),
initialised:false,
floatingPane: null,
postCreate: function() {
this.init();
},
init: function() {
console.debug("SearchDialog.init()", "start");
if ( this.initialised === false ) {
this.createSearchDialog();
}
//ne.trim.AppGlobals.searchDialog = this;
console.debug("SearchDialog.init()", "end");
},
createSearchDialog: function() {
var node = dojo.byId('searchbox');
floatingPane = new dojox.layout.FloatingPane({
title: "A floating pane",
resizable: true, dockable: true, constrainToContainer: true,
style: "position:absolute;top:100;right:100;width:400px;height:300px;z-index:100",
}, node );
this.initialised=true;
floatingPane.startup();
}
});

First of all, see the working example at jsFiddle: http://jsfiddle.net/phusick/3vTXW/
And now some explanation;) The DnD functionality of FloatingPane is achieved via dojo.dnd.Moveable class instantialized in pane's postCreate method. To constrain the movement of the FloatingPane you should use one of these moveables instead:
dojo.dnd.parentConstainedMoveable - to constrain by a DOM node
dojo.dnd.boxConstrainedMoveable - to constrain by co-ordinates: {l: 10, t: 10, w: 100, h: 100}
dojo.dnd.constrainedMoveable - to constrain by co-ordinates calculated in a provided function
For more details see aforementioned jsFiddle.
According to documentation you should call destroy() on Moveable instance to remove it, but as FloatingPane's original Moveable is not assigned to any object property, I do not destroy it, I just instantiate one of those three moveables on the same DOM node in a subclass:
var ConstrainedFloatingPane = dojo.declare(dojox.layout.FloatingPane, {
postCreate: function() {
this.inherited(arguments);
this.moveable = new dojo.dnd.move.constrainedMoveable(this.domNode, {
handle: this.focusNode,
constraints: function() {
return dojo.coords(dojo.body());
}
});
}
});
Now you can use ConstainedFloatingPane instead of dojox.layout.FloatingPane:
var floatingPane = new ConstrainedFloatingPane({
title: "A Constrained Floating Pane",
resizable: true
}, searchboxNode);

Related

startup is not getting called for Dojo Custom Widget

I created a Custom Widget in Dojo
return declare("DrawTools", [_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], {
templateString: template,
layers: [],
constructor: function (featureLayerArr) {
},
postCreate: function () {
},
startup: function () {
var menu = new DropDownMenu({ style: "display: none;" });
var menuItem1 = new MenuItem({
label: "Save",
iconClass: "dijitEditorIcon dijitEditorIconSave",
onClick: function () { alert('save'); }
});
menu.addChild(menuItem1);
var menuItem2 = new MenuItem({
label: "Cut",
iconClass: "dijitEditorIcon dijitEditorIconCut",
onClick: function () { alert('cut'); }
});
menu.addChild(menuItem2);
menu.startup();
var button = new DropDownButton({
label: "hello!",
name: "programmatic2",
dropDown: menu,
id: "progButton"
}, this.drawToolsMenuNode).startup();
},
startMenu: function () {
}
});
Wdiget template is as follows
<div>
<div data-dojo-attach-point="drawToolsMenuNode"></div>
</div>
I am instantiating Widget in another Custom Widget as follows
var drawTools = new DrawTools(this.allLayersArr);
drawTools.placeAt(this.drawToolsNode);
drawTools.startMenu();
startup method for DrawTools widget is not getting called.
Need help in this regard.
Offical definition from dojo
startup():
Probably the second-most important method in the Dijit lifecycle is the startup method. This method is designed to handle processing after any DOM fragments have been actually added to the document; it is not fired until after any potential child widgets have been created and started as well. This is especially useful for composite widgets and layout widgets.
When instantiating a widget programmatically, always call the widget's startup() method after placing it in the document. It's a common error to create widgets programmatically and then forget to call startup, leaving you scratching your head as to why your widget isn't showing up properly.
So as Kirill mentioned, you need to call the startup method.
The alternative solution would be moving widget instantiation logic from ::startup() to ::postCreate(), since ::postCreate() will be called for sure.

How to add custom layout in cytoscape.js 2.6 version

The API documentation (http://js.cytoscape.org/#extensions/api) says that cytoscape( type, name, extension ) whould register an extension.
It worked in v2.4 but doesn't work anymore in v2.6.
What is the right way to do it now ?
EDIT:
Here is what I do
;(function($$){ 'use strict';
var defaults = {
fit: true, // whether to fit the viewport to the graph
padding: 30, // the padding on fit
startAngle: 3/2 * Math.PI, // the position of the first node
counterclockwise: false, // whether the layout should go counterclockwise/anticlockwise (true) or clockwise (false)
minNodeSpacing: 10, // min spacing between outside of nodes (used for radius adjustment)
boundingBox: undefined, // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
avoidOverlap: true, // prevents node overlap, may overflow boundingBox if not enough space
height: undefined, // height of layout area (overrides container height)
width: undefined, // width of layout area (overrides container width)
concentric: function(node){ // returns numeric value for each node, placing higher nodes in levels towards the centre
return node.degree();
},
levelWidth: function(nodes){ // the variation of concentric values in each level
return nodes.maxDegree() / 4;
},
animate: false, // whether to transition the node positions
animationDuration: 500, // duration of animation in ms if enabled
ready: undefined, // callback on layoutready
stop: undefined // callback on layoutstop
};
function ConcentricLayout( options ){
console.log('INIT');
this.options = $$.util.extend({}, defaults, options);
}
ConcentricLayout.prototype.run = function(){
console.log('RUNNING');
// Run code
};
$$('layout', 'customconcentric', ConcentricLayout);
})( cytoscape );
And how I use it
var cy = cytoscape({
container: document.getElementById('cy'),
boxSelectionEnabled: false,
autounselectify: true,
elements: p,
layout: {
name: 'null',
stop: function() {
cy.elements('node.group').forEach(function( ele ){
var eles = ele.children();
eles.layout({
name: 'customgrid',
fit: false,
avoidOverlapPadding: 0,
columns: 2
});
});
cy.elements('node.machine').forEach(function( ele ){
var elesleft = ele.children('node.mod');
var elesright = ele.children('node.group');
var descendants = elesright.descendants();
if (elesleft.length > 0) {
var relpos = getRelativePositions(descendants);
elesright.forEach(function( ele ){
ele.relativePosition('x', 200);
});
setRelativePositions(relpos, cy);
elesleft.layout({
name: 'customgrid',
fit: false,
avoidOverlapPadding: 0,
columns: 1
});
}
});
cy.elements('node.machine, node.env').layout({
name: 'customconcentric',
fit: true
});
}
}
});
With 2.4.9 I see this in my browser's javascript console.
cytoscape.layout.custom.js:41 INIT
cytoscape.layout.custom.js:46 RUNNING
With 2.6.2, nothing happens.
The registration API is fine. You're relying on a private object that is not accessible:
this.options = $$.util.extend({}, defaults, options);
Only reference public APIs in the docs if you want your code to be compatible with newer versions: http://js.cytoscape.org
Use a proper debugger, like in Chrome. Your debugger should show you an error message when you reference non-existent objects or otherwise cause exceptions.

How to call an event when the dojo dgrid has been rendered completely?

We are using dojo without pagination and showing all records at once. We need to call a java script method when the entire grid has been rendered completely, so that the grid rows and cell can be used for DOM manipulation.
I am trying following code, but its not working.
aspect.after(grid,"dgrid-refresh-complete",function(){
});
grid.on("dgrid-refresh-complete", function(event){
});
dgrid-refresh-complete is implemented specifically in OnDemandList and Pagination. If you're using the SingleQuery mixin instead (as in the tutorial for 0.3 or 0.4), it should be feasible to institute the same kind of event as follows:
var self = this;
// existing code from refresh...
// when(...) (via dojo/when) should only be necessary here for dgrid 0.3
var promise = when(this._trackError(/* existing code from refresh */));
promise.then(function () {
on.emit(self.domNode, 'dgrid-refresh-complete', {
bubbles: true,
cancelable: false,
grid: self
});
});
return promise;
So, for example, in 0.3, SingleQuery's refresh method would look like this:
refresh: function () {
var self = this;
// First defer to List#refresh to clear the grid's
// previous content
this.inherited(arguments);
if (!this.store) {
return;
}
var promise = when(this._trackError(function () {
var queryOptions = self.get('queryOptions'),
results = self.store.query(
self.query, queryOptions);
return self.renderArray(
results, null, queryOptions);
}));
promise.then(function () {
on.emit(self.domNode, 'dgrid-refresh-complete', {
bubbles: true,
cancelable: false,
grid: self
});
});
return promise;
}

ArcGis javascript api 3.5 how to set visibility of a feature layer

i am using ArcGis javascript api 3.5 and my code is
map = new esri.Map("mapDiv", {
basemap: "streets",
center: [-112.07102547942392, 46.75909704205151],
zoom: 12,
slider: false,
infoWindow: infoWindow
});
var featureLayer = new esri.layers.FeatureLayer("http:/abc/arcgis/rest/services/MTARNG/MapServer/1", {
mode: esri.layers.FeatureLayer.MODE_SNAPSHOT,
infoTemplate: templateFuze,
outFields: ["*"]
});
var featureLayer1 = new esri.layers.FeatureLayer("http://abc/arcgis/rest/services/MTARNG/MapServer/0", {
mode: esri.layers.FeatureLayer.MODE_SNAPSHOT,
infoTemplate: templateParcel,
outFields: ["*"]
});
var featureLayer2 = new esri.layers.FeatureLayer("http://abc/arcgis/rest/services/MTARNG/MapServer/2", {
mode: esri.layers.FeatureLayer.MODE_SNAPSHOT,
infoTemplate: templateGrid,
outFields: ["*"]
});
Ext.create('Ext.form.Panel', {
width: 400,
height: 600,
bodyPadding: 10,
renderTo: Ext.get('LayerDiv'),
items: [{
xtype: 'checkboxgroup',
columns: 1,
vertical: true,
items: layerInfo,
listeners: {
change: {
fn: function (checkbox, checked) {
for (var i = 0; i < checkbox.items.items.length; i++) {
if (checkbox.items.items[i].checked) {
//visible true checkbox.items.items[0].boxLabel
}
else {
//visible false
}
}
}
}
}
}]
});
});
So i am trying to set the visibilty of the layer but i am not able to do. after that how to refresh the map ?
I got some function but it is working e.g.- visibleAtMapScale = false,
defaultVisibility = false and for refreshing i got only map.resize=true;
What else i can try to achive this functionality.
You can change the visibility of an layer using the hide() and show() functions - FeatureLayer inherits them from GraphicsLayuer (Which inherits them from Layer). So in your example, given featureLayer is a global variable it should be in scope when the event fires so you could just do:
featureLayer.hide();
and
featureLayer.show();
You don't need to refresh the map, it will happen automatically.
Simon
When creating a new FeatureLayer, you can specify the default visibility using the optional parameters. The default is true.
var featureLayer = new esri.layers.FeatureLayer("http:/.../MapServer/1",
{visible:false}
});
To set the visibility of the existing layer, you can use the setVisibility() method.
featureLayer.setVisibility(false);
If you want to enable intellisense support in Visual Studio you can download and reference the code assist plugin from the Esri website. There is a help page about it here with links to the various versions supported and how to use it from VS.
If you just want to get the VS2012 version for v3.5 of the JS API it is here and to reference it:
If working in an HTML file, add a script tag to add a reference to the code assist
<script type='text/javascript' src='path_to_vsdoc.js'></script>
If working in a JavaScript file, add a reference directive to the VSDoc file:
/// <reference path="~/Scripts/esri-jsapi-vsdoc.js" />

FullCalendar and Flot Resize Conflict

I've successfully integrated both a Flot line graph and an instance of FullCalendar into my site. They are both on separate pages (although the pages are loaded into a div via AJAX).
I've added the Flot Resize plugin and that works perfectly, re-sizing the line graph as expected. However, it seems to cause an error when resizing the calendar.
Even if I load the calendar page first, when I resize the window I get this error in the console (also, the calendar does not resize correctly):
TypeError: 'undefined' is not an object (evaluating 'r.w=o!==c?o:q.width()')
I was struggling to work out where the error was coming from, so I removed the link to the Flot Resize JS and tried again. Of course the line graph does not resize, but when resizing the calendar, it works correctly.
The div containers for the two elements have different names and the resize function is called from within the function to draw the line graph (as required).
I have tried moving the link to the Flot Resize plugin into different places (i.e. above/below the fullCalendar JS, into the template which holds the graph), but all to no avail.
Does anyone have any idea where the conflict might be and how I might solve it??
Thanks very much!
EDIT: It seems that the error is also triggered when loading the line graph (flot) page AFTER the fullcalendar page even without resizing the window.... Now I am very confused!
EDIT 2: The code which draws the line graph. The function is called on pageload and recieves the data from JSON pulled off the server. When the graph is loaded, I still get the error about shutdown() being undefined.
function plotLineGraph(theData){
var myData = theData['data'];
var myEvents = theData['events'];
var myDates = theData['dates'];
var events = new Array();
for (var i=0; i<myEvents.length; i++) {
events.push(
{
min: myEvents[i][0],
max: myEvents[i][1],
eventType: "Calendar Entry",
title: myEvents[i][2],
description: myEvents[i][3]
}
);
}
function showTooltip(x, y, contents) {
$('<div id="tooltip">' + contents + '</div>').css( {
position: 'absolute',
display: 'none',
top: y + 5,
left: x + 5,
border: '1px solid #fdd',
padding: '2px',
'background-color': 'black',
opacity: 0.80
}).appendTo("body").fadeIn(200);
}
var previousPoint = null;
$("#placeholder").bind("plothover", function (event, pos, item) {
$("#x").text(pos.x.toFixed(2));
$("#y").text(pos.y.toFixed(2));
if ($("#enableTooltip:checked").length == 0) {
if (item) {
if (previousPoint != item.dataIndex) {
previousPoint = item.dataIndex;
$("#tooltip").remove();
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
if(item.series.label != null){
showTooltip(item.pageX, item.pageY,
item.series.label + " of " + y);
}
}
}
else {
$("#tooltip").remove();
previousPoint = null;
}
}
});
var d1 = [
myData[0], myData[1], myData[2], myData[3], myData[4],
myData[5], myData[6], myData[7], myData[8], myData[9],
myData[10], myData[11], myData[12], myData[13], myData[14],
myData[15], myData[16], myData[17], myData[18], myData[19],
myData[20], myData[21], myData[22], myData[23], myData[24],
myData[25], myData[26], myData[27], myData[28], myData[29]
];
var markings = [
{ color: '#FFBDC1', yaxis: { from: 0, to: 2 } },
{ color: '#F2E2C7', yaxis: { from: 2, to: 3.5 } },
{ color: '#B6F2B7', yaxis: { from: 3.5, to: 5 } }
];
$.plot($("#placeholder"), [
{label: "Average Daily Rating", data: d1, color: "black"}
], {
events: {
data: events,
},
series: {
lines: { show: true },
points: { show: true }
},
legend: { show: true, container: '#legend-holder' },
xaxis: {
ticks:[
myDates[0], myDates[1], myDates[2], myDates[3], myDates[4],
myDates[5], myDates[6], myDates[7], myDates[8], myDates[9],
myDates[10], myDates[11], myDates[12], myDates[13], myDates[14],
myDates[15], myDates[16], myDates[17], myDates[18], myDates[19],
myDates[20], myDates[21], myDates[22], myDates[23], myDates[24],
myDates[25], myDates[26], myDates[27], myDates[28], myDates[29]
],
},
yaxis: {
ticks: 5,
min: 0,
max: 5
},
grid: {
backgroundColor: { colors: ["#fff", "#eee"] },
hoverable: true,
clickable: true,
markings: markings
},
selection: {
color: 'white',
mode: 'x'
},
});
$('#placeholder').resize();
$('#placeholder').shutdown();
}
EDIT 3:
The calendar is called like this:
function showCalendar() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#fullcalendar').fullCalendar({
header: {
left: 'prev',
center: 'title',
right: 'next'
},
clickable: true,
firstDay: 1,
eventSources: [
{
url: '/populate-calendar/{{theProductUuid}}/',
color: 'black',
data: {
text: 'text'
}
}
],
eventClick: function(calEvent, jsEvent, view) {
var startDate = $.fullCalendar.formatDate(calEvent.start, 'yyyy-MM-dd');
var endDate = $.fullCalendar.formatDate(calEvent.end, 'yyyy-MM-dd');
var eventId = calEvent.uuid;
$('#modal-event-title').text(calEvent.title);
$('#edit-event-name').val(calEvent.title);
$('#edit-start-date').val(startDate);
$('#edit-end-date').val(endDate);
$('#edit-event-text').val(calEvent.text);
$('#edit-event-btn').attr('data-uuid', eventId);
$('#modal-edit-event').on('click', '#delete-btn', function(){
deleteCalendarEvent(eventId);
});
$('#modal-edit-event').modal();
},
});
}
The AJAX to load the page containing the flot chart:
function loadDetailedReports(uuid){
$('#product-content').fadeOut('slow', function(){
$('#product-content').empty();
$('#whole-product-sub-nav .active').removeClass('active');
$('#detailed-reports-content').load('/detailed-reports/' + uuid + '/', function(){
$('#detailed-reports-btn').addClass('active');
$('#detailed-reports-content').fadeIn('slow', function(){
if (authorized){
setLocationHash('loadDetailedReports&' + uuid);
getChartData(uuid);
} else {
setLocationHash('');
}
});
});
});
}
And the AJAX to load the page containing the calendar:
function loadCalendar(uuid){
$('#detailed-reports-content').empty().hide();
$('#product-content').fadeOut('slow', function(){
$('#whole-product-sub-nav .active').removeClass('active');
$('#product-content').load('/calendar/' + uuid + '/', function(){
$('#calendar-btn').addClass('active');
$('#product-content').fadeIn('slow', function(){
if (authorized){
setLocationHash('loadCalendar&' + uuid);
} else {
setLocationHash('');
}
showCalendar();
});
});
});
}
The calls to .resize and .shutdown are there because I was under the impression that they are necessary to achieve the resizing function and in response to your earlier comment regarding shutdown...... They're quite possibly n00b errors........?!?!
It looks like this is triggering on line 198 of jquery-resize:
data.w = w !== undefined ? w : elem.width();
This sounds like a race-condition stemming from the way you load different content into the same div. Flot binds the resize event to the chart div, and only un-binds it if the plot is destroyed cleanly.
EDIT: Looking at your code, my first suggestion would be to get rid of the resize and shutdown calls at the end of plotLineGraph. The resize plugin doesn't require any setup; it hooks into Flot to attach automatically to any new plot. So your call to resize is actually to jQuery's resize event trigger, which may be what's causing the error.
EDIT #2: I'm still not clear on your structure, but to generalize: anywhere that you might be getting rid of #placeholder (via emptying its parent or anything like that) you should first call shutdown on the plot object. If you aren't keeping a reference to it, you can do it like this: $("#placeholder").data("plot").shutdown(); but then have to account for the fact that it's undefined prior to the creation of your first plot.
If that still doesn't work, I'd need to see a live (simplified) example to make any further suggestions.