"orion" is undefined when integrating orion editor in dojo - dojo

I am new to dojo and I am trying to integrate orion editor(build downloaded from http://download.eclipse.org/orion/) in dojo but I get the error "orion" is undefined.
The code looks like below:
HTML file for placing editor
<div data-dojo-attach-point="embeddedEditor"></div>
A JS file
require([
"dojo/_base/declare",
"dijit/_WidgetBase",
"editorBuild/code_edit/built-codeEdit-amd",
"dijit/_TemplatedMixin",
"dojo/text!orionEditor.html"
], function(declare,_WidgetBase,
codeEditorAmd, _TemplatedMixin,template){
declare("orionEditor", [_WidgetBase,
_TemplatedMixin], {
templateString: template,
postCreate: function(){
var codeEdit = new orion.codeEdit();
var contents = '';
codeEdit.create({parent: this.embeddedEditor, contentType: "application/javascript", contents: contents}).
then(function(editorViewer) {
if (editorViewer.settings) {
editorViewer.settings.contentAssistAutoTrigger = true;
editorViewer.settings.showOccurrences = true;
}
});
}
});
});
The orion editor build is placed in editorBuild folder.
Standalone orion works fine - http://libingw.github.io/OrionCodeEdit/
When integrating with dojo I am not sure why orion is undefined.
Any help would be much appreciated.

If you want using orion name in amd module then it has to be defined as parameter in function passed as require's callback.
Check this guide - it has 2 solutions for using orion with amd modules.
Option 1 - define bundles once and use shorter name in all modules you need them:
require.config({
bundles: {
"editorBuild/code_edit/built-codeEdit-amd": ["orion/codeEdit", "orion/Deferred"]
}
});
require(
["orion/codeEdit", "orion/Deferred"],
function(mCodeEdit, Deferred) {
var codeEdit = new mCodeEdit();
var contents = 'var foo = "bar";';
codeEdit.create({parent: "embeddedEditor"/*editor parent node id*/})
.then(function(editorViewer) {
editorViewer.setContents(contents, "application/javascript");
});
});
Option 2 - nested require:
require(["editorBuild/code_edit/built-codeEdit-amd"], function() {
require(["orion/codeEdit", "orion/Deferred"], function(mCodeEdit, Deferred) {
var codeEdit = new mCodeEdit();
var contents = 'var foo = "bar";';
codeEdit.create({parent: "embeddedEditor"/*editor parent node id*/})
.then(function(editorViewer) {
editorViewer.setContents(contents, "application/javascript");
});
});
});
Note: you can replace mCodeEdit with any unique name (That wouldn't shadow other objects/modules)

Related

ArcGIS Online WebMap authentication timeout

I have an ArcGIS Online public account and add WebMap to my website.
My ArcGIS Online WebMap looks like this ESRI's sample: LINK
And I am trying to add my WebMap to my website like this ESRI's reference page. You will see there is a map in the center of page: LINK
My WebMap is displayed on my webpage well. When I access my webpage, my WebMap asks my ID and Password. If I entered it, then it shows my map.
However, my question is, if I moved to different page and then come back to map page, it asks again. Is it possible to set a timeout so I don't have to sign in everytime I access the page?
The reason I asked this question is that to find out if there were a way to reduce my code simple and work on code in front-end.
I've researched OAuth that ESRI provided and I ended up using esri/IdentityManager. There were references to use esri/IdentityManager package; however there were no sample code to using it with personal WebMap which used arcgisUtils.createMap
So here is sample code that I worked:
require([
"dojo/parser",
"dojo/ready",
"dijit/layout/BorderContainer",
"dijit/layout/ContentPane",
"dojo/dom",
"esri/map",
"esri/urlUtils",
"esri/arcgis/utils",
"esri/dijit/Legend",
"esri/dijit/LayerList",
"esri/graphic",
"esri/symbols/PictureMarkerSymbol",
"esri/symbols/TextSymbol",
"esri/geometry/Point",
"esri/dijit/Scalebar",
"dojo/_base/unload",
"dojo/cookie",
"dojo/json",
"esri/config",
"esri/IdentityManager",
"esri/layers/FeatureLayer",
"dojo/domReady!"
], function (
parser,
ready,
BorderContainer,
ContentPane,
dom,
Map,
urlUtils,
arcgisUtils,
Legend,
LayerList,
Graphic,
PictureMarkerSymbol,
TextSymbol,
Point,
Scalebar,
baseUnload,
cookie,
JSON,
esriConfig,
esriId,
FeatureLayer
) {
var mapOptions = {
basemap: "topo",
autoResize: true, // see http://forums.arcgis.com/threads/90825-Mobile-Sample-Fail
center: [currentPosition.lng, currentPosition.lat],
zoom: 15,
logo: false
};
// cookie/local storage name
var cred = "esri_jsapi_id_manager_data";
// store credentials/serverInfos before the page unloads
baseUnload.addOnUnload(storeCredentials);
// look for credentials in local storage
loadCredentials();
parser.parse();
esriConfig.defaults.io.proxyUrl = "/proxy/";
//Create a map based on an ArcGIS Online web map id
arcgisUtils.createMap('PUT-YOUR-ESRI-KEY', "esriMapCanvas", { mapOptions: mapOptions }).then(function (response) {
var map = response.map;
// add a blue marker
var picSymbol = new PictureMarkerSymbol(
'http://static.arcgis.com/images/Symbols/Shapes/RedPin1LargeB.png', 50, 50);
var geometryPoint = new Point('SET YOUR LAT', 'SET YOUR LONG');
map.graphics.add(new Graphic(geometryPoint, picSymbol));
//add the scalebar
var scalebar = new Scalebar({
map: map,
scalebarUnit: "english"
});
//add the map layers
var mapLayers = new LayerList({
map: map,
layers: arcgisUtils.getLayerList(response)
}, "esriLayerList");
mapLayers.startup();
//add the legend. Note that we use the utility method getLegendLayers to get
//the layers to display in the legend from the createMap response.
var legendLayers = arcgisUtils.getLegendLayers(response);
var legendDijit = new Legend({
map: map,
layerInfos: legendLayers
}, "esriLegend");
legendDijit.startup();
});
function storeCredentials() {
// make sure there are some credentials to persist
if (esriId.credentials.length === 0) {
return;
}
// serialize the ID manager state to a string
var idString = JSON.stringify(esriId.toJson());
// store it client side
if (supports_local_storage()) {
// use local storage
window.localStorage.setItem(cred, idString);
// console.log("wrote to local storage");
}
else {
// use a cookie
cookie(cred, idString, { expires: 1 });
// console.log("wrote a cookie :-/");
}
}
function supports_local_storage() {
try {
return "localStorage" in window && window["localStorage"] !== null;
} catch (e) {
return false;
}
}
function loadCredentials() {
var idJson, idObject;
if (supports_local_storage()) {
// read from local storage
idJson = window.localStorage.getItem(cred);
}
else {
// read from a cookie
idJson = cookie(cred);
}
if (idJson && idJson != "null" && idJson.length > 4) {
idObject = JSON.parse(idJson);
esriId.initialize(idObject);
}
else {
// console.log("didn't find anything to load :(");
}
}
});

Dojo _TemplatedMixin: changing templateString

How do I change the template of a widget, using mixins dijit/_TemplatedMixin and dijit/_WidgetsInTemplateMixin, at a later time (not in the constructor)?
My scenario is that the widget must make a call to the server to get data, and the callback function will then merge the data with a template file and then the resulting template should be used for the templateString. The widget should update its contents at this point.
Setting the templateString and calling buildRendering() has no effect.
Here is a simplified version of my code:
define([
"dojo/_base/declare",
"dojo/_base/lang",
"dijit/_WidgetBase",
"dijit/_TemplatedMixin",
"dijit/_WidgetsInTemplateMixin",
],
function(declare, lang, _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin) {
return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], {
constructor: function(id) {
this.id = id;
this.templateString = "<div>Loading...</div>";
//use xhr to call REST service to get data.
//dataLoadedCallback is executed with response data
...
},
dataLoadedCallback : function(data) {
this.destroyRendering();
//render a templateString using the data response from the rest call
this.templateString = "<div>Data is loaded. Name:" + data.name + "</div>"
this.buildRendering();
},
});
});
You cannot do such thing. The template is parsed only once before postCreate method.
However there is few things you can do:
Create a non-ui widget which will do the XHR call. When this non-ui widget get the XHR response it creates the UI widget with the correct templateString
Or use dojo/dom-construct. It contains a toDom method which you can use for converting your string into nodes. Then you can append that to the widget.
Note: this will not parse any data-dojo attributes
You could also directly inject the received templateString into the widget domNode:
dataLoadedCallback : function(data) {
this.domNode.innerHTML = "<div>Data is loaded. Name:" + data.name + "</div>";
//you might be able to parse the content (if you have subwidgets) using dojo/parse
},
Last but not least, here is a util I wrote for my self. It allow to parse any templateString at any time (like dojo does on widget creation)
define([
'dojo/dom-construct',
'dojo/string',
'dijit/_AttachMixin',
'dijit/_TemplatedMixin'
], function(domConstruct, string,
_AttachMixin, _TemplatedMixin) {
// summary:
// provide an utility to parse a template a runtime (and create attach point, atach events, etc...)
// Copyright: Benjamin Santalucia
var GET_ATTRIBUTE_FUNCTION = function(n, p) { return n.getAttribute(p); },
_TemplateParserMixin = function() {};
_TemplateParserMixin.prototype = {
parseTemplate: function(template, data, container, position, transformer) {
// summary:
// parse the template exactly as dojo will nativly do with a templateString
if(this._attachPoints === undefined) {
this._attachPoints = [];
}
if(this._attachEvents === undefined) {
this._attachEvents = [];
}
var nodes,
x,
len,
newTemplate = string.substitute(template, data, transformer),
node = domConstruct.toDom(_TemplatedMixin.prototype._stringRepl.call(this, newTemplate));
if(node.nodeName === '#document-fragment') {
node = node.firstChild;
}
//parse all nodes and create attach points and attach events
nodes = node.getElementsByTagName('*');
len = nodes.length;
for(x = -1; x < len; x++) {
_AttachMixin.prototype._processTemplateNode.call(this, x < 0 ? node : nodes[x], GET_ATTRIBUTE_FUNCTION, _AttachMixin.prototype._attach);
}
if(container) {
domConstruct.place(node, container, position);
}
return node;
}
};
return _TemplateParserMixin;
});
Usage is:
returnedNode = w.parseTemplate(newTemplateString, {
templatePlaceHolderName: 'foo' //for teplate with placeholders like ${templatePlaceHolderName}
}, domNodeToInsertIn, 'only'); //last parameter is same as dojo/dom-construct::place() >> last, first, before, after, only

Durandal, get path of the current module

Is there a way in Durandal to get the path of the current module? I'm building a dashboard inside of a SPA and would like to organize my widgets in the same way that durandal does with "FolderWidgetName" and the folder would contain a controller.js and view.html file. I tried using the getView() method in my controller.js file but could never get it to look in the current folder for the view.
getView(){
return "view"; // looks in the "App" folder
return "./view"; // looks in the "App/durandal" folder
return "/view"; // looks in the root of the website
return "dashboard/widgets/htmlviewer/view" //don't want to hard code the path
}
I don't want to hardcode the path inside of the controller
I don't want to override the viewlocator because the rest of the app still functions as a regular durandal spa that uses standard conventions.
You could use define(['module'], function(module) { ... in order to get a hold on the current module. getView() would than allow you to set a specific view or, like in the example below, dynamically switch between multiple views.
define(['module'], function(module) {
var roles = ['default', 'role1', 'role2'];
var role = ko.observable('default');
var modulePath = module.id.substr(0, module.id.lastIndexOf('/') +1);
var getView = ko.computed(function(){
var roleViewMap = {
'default': modulePath + 'index.html',
role1: modulePath + 'role1.html',
role2: modulePath + 'role2.html'
};
this.role = (role() || 'default');
return roleViewMap[this.role];
});
return {
showCodeUrl: true,
roles: roles,
role: role,
getView: getView,
propertyOne: 'This is a databound property from the root context.',
propertyTwo: 'This property demonstrates that binding contexts flow through composed views.',
moduleJSON: ko.toJSON(module)
};
});
Here's a live example http://dfiddle.github.io/dFiddle-1.2/#/view-composition/getView
You can simply bind your setup view to router.activeRoute.name or .url and that should do what you are looking for. If you are trying to write back to the setup viewmodels property when loading you can do that like below.
If you are using the revealing module you need to define the functions and create a module definition list and return it. Example :
define(['durandal/plugins/router', 'view models/setup'],
function(router, setup) {
var myObservable = ko.observable();
function activate() {
setup.currentViewName = router.activeRoute.name;
return refreshData();
}
var refreshData = function () {
myDataService.getSomeData(myObservable);
};
var viewModel = {
activate: activate,
deactivate: deactivate,
canDeactivate: canDeactivate
};
return viewModel;
});
You can also reveal literals, observables and even functions directly while revealing them -
title: ko.observable(true),
desc: "hey!",
canDeactivate: function() { if (title) ? true : false,
Check out durandal's router page for more info on what is available. Also, heads up Durandal 2.0 is switching up the router.
http://durandaljs.com/documentation/Router/
Add an activate function to your viewmodel as follows:
define([],
function() {
var vm = {
//#region Initialization
activate: activate,
//#endregion
};
return vm;
//#region Internal methods
function activate(context) {
var moduleId = context.routeInfo.moduleId;
var hash = context.routeInfo.hash;
}
//#endregion
});

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" />

Unable to print output to the console in dojo

I'm a beginner in dojo, and I'm trying to print the output to console using dojo code. But I don't what's the problem in the following code, and how can I print the output to the console?
<html>
<head>
<script type = "text/javascript" src = "dojo/dojo.js" data-dojo-config = "async: true, isDebug : true" >
</script>
</head>
<body>
<h1 id = "greeting">Hello</h1>
<script>
define(["dojo/dom"],function(dom) {
var Twitter = declare(null, {username:"defaultusername",
say :function(msg)
{
console.log("Hello "+msg);
}
});
var myInstance = new Twitter();
myInstance.say("Dojo");
});
</script>
</body>
</html>
Use require instead of define:
<script>
require(["dojo/dom", "dojo/_base/declare"], function(dom, declare) {
var Twitter = declare(null, {
username: "defaultusername",
say :function(msg) {
console.log("Hello "+msg);
}
});
var myInstance = new Twitter();
myInstance.say("Dojo");
});
</script>
Console works, but your code inside callback function in declare is not being executed until you require it.
You cannot define in inline script code, that is meant to be a class define, put in the topmost line of a class-file, meaning define maps the filename to the returned value of its function.
This means, if you have
dojo_toolkit /
dojo/
dijit/
dojox/
libs/
myWidgets/
foo.js
And foo.js reads
define(["dijit._Widget"], function(adijit) {
return declare("libs.myWidgets.foo", [adijit], function() {
say: function(msg) { console.log(msg); }
});
});
Then a new module is registered, called libs / myWidgets / foo. You should make sure that the returned declare's declaredClass inside each define matches the file hierachy.
That being said, reason why define does not work for you is the explaination above. It is inline and has no src to guess the declaredClass name from. Rewrite your code to define("aTwitterLogger", [":
define("aTwitterLogger", ["dojo/_base/declare", "dojo/dom"],function(declare, dom) {
var Twitter = declare(null, {
username:"defaultusername",
say :function(msg)
{
console.log("Hello "+msg);
}
});
var myInstance = new Twitter();
myInstance.say("Dojo");
});