Writing SAPUI5 control renderer in "sap.ui.define" style - sapui5

I'd like to write custom control in a new sap.ui.define fashion. I have a problem implementing control renderer in a separate file: it seems one have to put bExport = true, while this is forbidden by SAP.
bExport: whether an export to global names is required - should be used by SAP-owned code only
I haven't found any examples of renderer implementations that doesn't utilize export hack and I have a doubt if such a way ever exists.
I've got some suggestions, but they doesn't fully satisfy me:
Ignore SAP requirement and use bExport = true. Pros: highest reuse of SAP code and generally follow standard logic. Cons: avoiding official recommendations.
Explicitly set my.namespace.control.GreatControlRenderer from within factory function. Pros: simple, doesn't touch bExport. Cons: breaks modular design (as module actually sets global variable).
What is the best or recommended way to resolve this issue?
Technically, an object reference available for public use is created inside framework code with jQuery.sap.setObject method, both in:
sap.ui.core.Control.extend() -- actually within parent class method
sap.ui.base.Metadata.createClass()
sap.ui.define(/* bExport = */ true)
This method creates hierarchy of objects in global scope by object dot.separated.qualified.name as follows:
jQuery.sap.setObject = function(sName, vValue, oContext) {
var oObject = oContext || window,
aNames = (sName || "").split("."),
l = aNames.length,
i;
if (l > 0) {
for (i = 0; oObject && i < l - 1; i++) {
if (!oObject[aNames[i]]) {
oObject[aNames[i]] = {};
}
oObject = oObject[aNames[i]];
}
oObject[aNames[l - 1]] = vValue;
}
};

First, your Renderer is an Object with a render function. It's a static function. Return this Renderer from your module.
sap.ui.define([], function(){
"use strict";
var MyControlRenderer = {};
MyControlRenderer.apiVersion = 2;
MyControlRenderer.render = function(oRm, oControl){
// Render your control
};
return MyControlRenderer;
});
Then in your control, you import your Renderer object and assign it to the renderer property of your control like this:
sap.ui.define([
"sap/ui/core/Control",
"./MyControlRenderer"
], function(Control, MyControlRenderer) {
"use strict";
var MyControl = Control.extend("bla.MyControl", {
metadata: {
// ...
},
renderer: MyControlRenderer
});
return MyControl;
});
In this example the renderer is in the same directory as the control.

Related

ol-cesium: Is there a way to select a feature in ol-cesium and track it back to openlayers features?

I have a geojson that was added as a feature vector to openlayer. All the geojson in their properties section have some additional information that I want to display on clicking a feature (eg a popup) in 3d space. I used the ol-cesium overlay example to create a pop but there isn't a way to get the feature-geojson properties just with 3d(ol-cesium) enabled.
Are there any approach to get the feature details on clicking a feature in 3d space?
figured it out I think I had to do some think like this .
private getOlFeatureFromMouseLocationInOLCS(cesiumMouseEvent: any): OlFeature | undefined {
if (cesiumMouseEvent.position.x === 0 && cesiumMouseEvent.position.y === 0) {
return;
}
/**
//hoping the below two lines have bee defined early on .
this._ol3d = new OLCesium({ map: this._currentMap });
this.scene = this._ol3d.getCesiumScene();
**/
const pickedFeature = this.scene.pick(cesiumMouseEvent.position);
let olFeature: OlFeature;
if (pickedFeature.primitive) {
olFeature = (pickedFeature.primitive.olFeature)?pickedFeature.primitive.olFeature as OlFeature : undefined;
} else {
olFeature = undefined;
}
return olFeature;
}

telerik kendo treeview - prevent dragging outside of parent

I'm trying to prevent the dragging and dropping of nodes outside of the parent node ("LLCA") with no luck.
Any suggestions?
Image of Treeview
I ended up getting it to work using your code below:
function onDrop(e) {
var dst = e.destinationNode;
var first = $('.k-item:first');
var pos = e.dropPosition;
if (dst && dst.uid === first.uid && pos !== "over") {
e.setValid(false);
}
}
Lets define the treeview:
var tree = $("#tree").kendoTreeView({
dataSource :content,
dragAndDrop:true
}).data("kendoTreeView");
What I'm going to do is add a drop callback where I will control that:
We are not dropping outside the tree
We are not dropping before or after the first node of the tree
The definition of the tree would be:
var tree = $("#tree").kendoTreeView({
dataSource :content,
dragAndDrop:true,
drop :function (ev) {
var dst = tree.dataItem(ev.destinationNode);
var first = tree.dataItem(".k-item:first");
var pos = ev.dropPosition;
if (dst && dst.uid === first.uid && pos !== "over") {
console.log("invalid");
ev.setValid(false);
}
}
}).data("kendoTreeView");
Check http://docs.kendoui.com/api/web/treeview#drop for information on drop event.
Because I cannot comment on an answer, I will write my own.
User Mithrilhall asked about MVC wrappers, also the top answer only prevents movement to the root node.
I will attempt to answer both Mithrilhall and provide an example where you can only move a child within the context of its parent. To put it another way, to only allow children of any parent to change their order within the parent.
Firstly, for MithrilHall, this is how you get to the events in MVC.
#(Html.Kendo().TreeView()
.Name("ourTreeView")
.Events(e => e.Drop("treeViewDrop"))
There are other events in treeview, you can take a gander for yourself. The argument is the name of a javascript function. Here is an example javascript function for this MVC wrapper to prevent children from moving outside of their parent, but allowing them to still move within the parent.
<script type="text/javascript">
function treeViewDrop(dropEvent) {
var treeView = $("#ourTreeView").data("kendoTreeView");
var destination = treeView.dataItem(dropEvent.destinationNode);
var source = treeView.dataItem(dropEvent.sourceNode);
if (!(destination && destination.parentID == source.parentID)) {
dropEvent.setValid(false);
}
}
</script>
I had a parentID field modeled in my datasource. You could accomplish this in many ways. The dataItem method returns a kendo treeview item, so it has all of your modeled fields in it.
Also understand, this solution does not change the widget to show an X when you are moving to a place you cannot drop to. This is another problem with another solution.
I hope this helps, good luck!

jsTree Node Expand/Collapse

I ran into the excellent jstree jQuery UI plug in this morning. In a word - great! It is easy to use, easy to style & does what it says on the box. The one thing I have not yet been able to figure out is this - in my app I want to ensure that only one node is expanded at any given time. i.e. when the user clicks on the + button and expands a node, any previously expanded node should silently be collapsed. I need to do this in part to prevent the container div for a rather lengthy tree view from creating an ugly scrollbar on overflow and also to avoid "choice overload" for the user.
I imagine that there is some way of doing this but the good but rather terse jstree documentation has not helped me to identify the right way to do this. I would much appreciate any help.
jsTree is great but its documentation is rather dense. I eventually figured it out so here is the solution for anyone running into this thread.
Firstly, you need to bind the open_node event to the tree in question. Something along the lines of
$("tree").jstree({"themes":objTheme,"plugins":arrPlugins,"core":objCore}).
bind("open_node.jstree",function(event,data){closeOld(data)});
i.e. you configure the treeview instance and then bind the open_node event. Here I am calling the closeOld function to do the job I require - close any other node that might be open. The function goes like so
function closeOld(data)
{
var nn = data.rslt.obj;
var thisLvl = nn;
var levels = new Array();
var iex = 0;
while (-1 != thisLvl)
{
levels.push(thisLvl);
thisLvl = data.inst._get_parent(thisLvl);
iex++;
}
if (0 < ignoreExp)
{
ignoreExp--;
return;
}
$("#divElements").jstree("close_all");
ignoreExp = iex;
var len = levels.length - 1;
for (var i=len;i >=0;i--) $('#divElements').jstree('open_node',levels[i]);
}
This will correctly handle the folding of all other nodes irrespective of the nesting level of the node that has just been expanded.
A brief explanation of the steps involved
First we step back up the treeview until we reach a top level node (-1 in jstree speak) making sure that we record every ancestor node encountered in the process in the array levels
Next we collapse all the nodes in the treeview
We are now going to re-expand all of the nodees in the levels array. Whilst doing so we do not want this code to execute again. To stop that from happening we set the global ignoreEx variable to the number of nodes in levels
Finally, we step through the nodes in levels and expand each one of them
The above answer will construct tree again and again.
The below code will open the node and collapse which are already opened and it does not construct tree again.
.bind("open_node.jstree",function(event,data){
closeOld(data);
});
and closeOld function contains:
function closeOld(data)
{
if($.inArray(data.node.id, myArray)==-1){
myArray.push(data.node.id);
if(myArray.length!=1){
var arr =data.node.id+","+data.node.parents;
var res = arr.split(",");
var parentArray = new Array();
var len = myArray.length-1;
for (i = 0; i < res.length; i++) {
parentArray.push(res[i]);
}
for (var i=len;i >=0;i--){
var index = $.inArray(myArray[i], parentArray);
if(index==-1){
if(data.node.id!=myArray[i]){
$('#jstree').jstree('close_node',myArray[i]);
delete myArray[i];
}
}
}
}
}
Yet another example for jstree 3.3.2.
It uses underscore lib, feel free to adapt solution to jquery or vanillla js.
$(function () {
var tree = $('#tree');
tree.on('before_open.jstree', function (e, data) {
var remained_ids = _.union(data.node.id, data.node.parents);
var $tree = $(this);
_.each(
$tree
.jstree()
.get_json($tree, {flat: true}),
function (n) {
if (
n.state.opened &&
_.indexOf(remained_ids, n.id) == -1
) {
grid.jstree('close_node', n.id);
}
}
);
});
tree.jstree();
});
I achieved that by just using the event "before_open" and close all nodes, my tree had just one level tho, not sure if thats what you need.
$('#dtree').on('before_open.jstree', function(e, data){
$("#dtree").jstree("close_all");
});

How do I submit a form using a store under ExtJs?

Is there a way to have a form submit create an object in a store under ExtJs 4?
It seems strange to me that the grid is built completely around the store mechanism and I see no obvious way to plug a form into a store. But I am most likely just missing something.
You can add a model instance to a store upon form submit using this code:
onSaveClick: function()
{
var iForm = this.getFormPanel().getForm(),
iValues = iForm.getValues(),
iStore = this.getTasksStore();
iStore.add( iValues );
},
This is within an MVC controller, so this is the controller.
For model editing, you can 'bind' a form to a model instance using loadRecord:
iFormPanel.loadRecord( this.selection );
You can then update the model instance using updateRecord():
iFormPanel.getForm().updateRecord();
Just for fun (and as it might help some), it is similar to the following code:
onSaveClick: function()
{
var iForm = this.getFormPanel().getForm(),
iRecord = iForm.getRecord(),
iValues = iForm.getValues();
iRecord.set ( iValues );
},
If your store is has autoSync: true. An Update (or Create) call will be made via the configured proxy. If there's no autoSync, you'll have to sync your store manually.
You can subclass Ext.form.action.Action to provide load/save actions for a Form to be performed on a Store. The only gotcha is that somehow there's no "official" way to select any non-standard Action in Ext.form.Basic, so I'd suggest an unofficial override:
Ext.define('Ext.form.Advanced', {
override: 'Ext.form.Basic',
submit: function(options) {
var me = this,
action;
options = options || {};
action = options.submitAction || me.submitAction;
if ( action ) {
return me.doAction(action, options);
}
else {
return me.callParent(arguments);
}
},
load: function(options) {
var me = this,
action;
options = options || {};
action = options.loadAction || me.loadAction;
if ( action ) {
return me.doAction(action, options);
}
else {
return me.callParent(arguments);
}
}
});
And, having created the Actions you need, you could then use them in a Form Panel:
Ext.define('My.form.Panel', {
extend: 'Ext.form.Panel',
requires: [ 'Ext.form.Advanced' ],
loadAction: 'My.load.Action',
submitAction: 'My.submit.Action',
...
});
There are other ways and shortcuts though.

What is the proper way in OpenLayers (OSM) to trigger a popup for a feature?

I have the feature ID, I can grab the marker layer on GeoRSS loadend, but I'm still not sure how to cause the popup to appear programmatically.
I'll create the popup on demand if that's necessary, but it seems as though I should be able to get the id of the marker as drawn on the map and call some event on that. I've tried using jQuery and calling the $(marker-id).click() event on the map elements, but that doesn't seem to be working. What am I missing?
Since I was asked for code, and since I presumed it to be boilerplate, here's where I am so far:
map = new OpenLayers.Map('myMap');
map.addLayer(new OpenLayers.Layer.OSM());
map.addLayer(new OpenLayers.Layer.GeoRSS(name,url));
//I've done some stuff as well in re: projections and centering and
//setting extents, but those really don't pertain to this question.
Elsewhere I've done a bit of jQuery templating and built me a nice list of all the points that are being shown on the map. I know how to do a callback from the layer loadend and get the layer object, I know how to retrieve my layer out of the map manually, I know how to iter over the layers collection and find my layer. So I can grab any of those details about the popup, but I still don't know how to go about using the built-in methods of the DOM or of this API to make it as easy as element.click() which is what I would prefer to do.
You don't have to click the feature to open a popup.
First you need a reference to the feature from the feature id. I would do that in the loadend event of the GeoRSS layer, using the markers property on the layer.
Assuming you have a reference to your feature, I would write a method which handles the automatic popup:
var popups = {}; // to be able to handle them later
function addPopup(feature) {
var text = getHtmlContent(feature); // handle the content in a separate function.
var popupId = evt.xy.x + "," + evt.xy.y;
var popup = popups[popupId];
if (!popup || !popup.map) {
popup = new OpenLayers.Popup.Anchored(
popupId,
feature.lonlat,
null,
" ",
null,
true,
function(evt) {
delete popups[this.id];
this.hide();
OpenLayers.Event.stop(evt);
}
);
popup.autoSize = true;
popup.useInlineStyles = false;
popups[popupId] = popup;
feature.layer.map.addPopup(popup, true);
}
popup.setContentHTML(popup.contentHTML + text);
popup.show();
}
fwiw I finally came back to this and did something entirely different, but his answer was a good one.
//I have a list of boxes that contain the information on the map (think google maps)
$('.paginatedItem').live('mouseenter', onFeatureSelected).live('mouseleave',onFeatureUnselected);
function onFeatureSelected(event) {
// I stuff the lookup attribute (I'm lazy) into a global
// a global, because there can be only one
hoveredItem = $(this).attr('lookup');
/* Do something here to indicate the onhover */
// find the layer pagination id
var feature = findFeatureById(hoveredItem);
if (feature) {
// use the pagination id to find the event, and then trigger the click for that event to show the popup
// also, pass a null event, since we don't necessarily have one.
feature.marker.events.listeners.click[0].func.call(feature, event)
}
}
function onFeatureUnselected(event) {
/* Do something here to indicate the onhover */
// find the layer pagination id
var feature = findFeatureById(hoveredItem);
if (feature) {
// use the pagination id to find the event, and then trigger the click for that event to show the popup
// also, pass a null event, since we don't necessarily have one.
feature.marker.events.listeners.click[0].func.call(feature, event)
}
/* Do something here to stop the indication of the onhover */
hoveredItem = null;
}
function findFeatureById(featureId) {
for (var key in map.layers) {
var layer = map.layers[key];
if (layer.hasOwnProperty('features')) {
for (var key1 in layer.features) {
var feature = layer.features[key1];
if (feature.hasOwnProperty('id') && feature.id == featureId) {
return feature;
}
}
}
}
return null;
}
also note that I keep map as a global so I don't have to reacquire it everytime I want to use it