How to target dynamically UI elements created with common.js with Appcelerator? - appcelerator-titanium

I am using Alloy and normally target an element in ui.xml with the contoller easily:
ui.xml
<Label id ="block1">
controller.js
$.block1.backgroundColor = "red";
But how can I target UI elements that are created within the controller filer (outside the function that creates the elements)? In particular, how can I later and dynamically set the background color of block2 to "green" when the elements are created by the for loop?
$.block2.backgroundColor = "green"; does not work as the element is not in the .xml file
function createBlocks(){
for (i=0;i<=27;i++){
var block = Ti.UI.createLabel({
id: "block"+ i,
backgroundColor: "red",
text: i,
width: 10,
left: 2 + (10 * i),
});
$.hammerListStats.add(block);
}
}

The block elements you are creating only life under that name inside the loop. You either need to store them in an array or use $.hammerListStats.children ot access them.
So either create an empty array before the loop var elements = [], use elements.push(block) inside the loop and use elements[0].text=... to change the text.
Or just use $.hammerListStats.children[0].text = ... to access them. This works fine as long as you don't have any other components inside $.hammerListStats or if you know their position you just add the value to it.

Elsewhere in your code you should be able to do something like this...
var i = 1;
var mytext = $["block"+ i].text;

Related

Is there any way to add a template doc at top of an another google document using google scripting?

I am trying to add a template doc into an existing google doc.The template is being added, but next time when i am trying to add the template again the template is appending at the bottom of the existing google doc but i want to insert the template at the top.
You can do this by getting the Body of one document and appending its child Elements to the current document.
function addtemplate() {
var thisDoc = DocumentApp.getActiveDocument();
var thisBody = thisDoc.getBody();
var templateDoc = DocumentApp.openById(''); //Pass in id of doc to be used as a template.
var templateBody = templateDoc.getBody();
for(var i=0; i<templateBody.getNumChildren();i++){ //run through the elements of the template doc's Body.
switch (templateBody.getChild(i).getType()) { //Deal with the various types of Elements we will encounter and append.
case DocumentApp.ElementType.PARAGRAPH:
thisBody.appendParagraph(templateBody.getChild(i).copy());
break;
case DocumentApp.ElementType.LIST_ITEM:
thisBody.appendListItem(templateBody.getChild(i).copy());
break;
case DocumentApp.ElementType.TABLE:
thisBody.appendTable(templateBody.getChild(i).copy());
break;
}
}
return thisDoc;
}
It sounds like your goal is to choose the position of the document where the content is added?
One option is to add the template at your current cursor location.
In the example below I have two functions. The first function creates a menu in Google Docs when I open the document (usually a few seconds delay).
The second function attempts to identify the position of my cursor. If it's successful it will insert the date at my cursor position.
Since I've created a menu item I don't have to go to the script editor to trigger this function.
function onOpen() {
// Add a menu item in Google Docs.
DocumentApp.getUi().createMenu('Insert Menu')
.addItem('Insert Current Date', 'insertCurrentDate')
.addToUi();
}
function insertCurrentDate() {
var cursor = DocumentApp.getActiveDocument().getCursor();
if (cursor) {
// Attempt to insert text at the cursor position. If insertion returns null,
// then the cursor's containing element doesn't allow text insertions.
var date = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd");
var element = cursor.insertText(date);
if (element) {
element.setBold(true);
} else {
DocumentApp.getUi().alert('Document does not allow inserted text at this location.');
}
} else {
DocumentApp.getUi().alert('Cannot find a cursor in the document.');
}
}
It's also possible that you want to clear the previous template before pasting the new one in? You can do that with the clear() function and then run the rest of your code.
body.clear()

QML Map: Large amount of displayed items

I have a performance issue while displaying large amounts MapItems on a Map provided by the QML Location module. I already asked the question here (https://forum.qt.io/topic/79229/large-amount-of-qml-mapitems), but nobody could help me, so I wanted to try it here once. I also found this question (How to use the QML/QtLocation module for displaying a large amount of offline data on a map?), but before adding another dependency, I wanted to see if my code can be improved so that QML can handle this situation without any help.
I am currently trying to plot a large amount of items onto a QML Map (30,000 - 120,000 points). These items shall be updated dependent of the position of a QSlider. Performance decreases strongly from about 1,000 items upwards, when I use 30,000 it takes several minutes until the QML Map has all the data visualized and is responsive again. I have a machine which is absolutely capable of fulfilling this task in general, so I think the problem is QML. I am using Qt 5.8.
Is there any way to improve this performance or is it just not possible with a QML-map to plot so many MapItems at a time? I tried MapCircles, Polylines, Polygons and MapQuickItems with images, but for me it seems like the performance issue just arises from adding this amount of MapItems, as I could not see a significant difference in processing time between these types.
I have more data on the map visualized, which should not be refreshed every time the QSlider is moved. Even though I tried just to clear all MapItems and add the new ones for performance tests, but even this did not improve the performance.
My code (a bit abstracted) looks like this:
///-------------- Widget.cpp-----------------///
void ProcessInput(int qslider_pos) {
QVariantList lat_vec;
QVariantList lon_vec;
// Fill vectors with lateral and longitudinal positions
// ...
// Clean current points on map and draw new ones
SendToQmlFuncRemovePoints();
SendToQmlFuncAddPoints(lat_vec, lon_vec);
}
void QmlConnector::SendToQmlFuncRemovePoints()
{
QVariant returnedValue;
QMetaObject::invokeMethod(QmlMapSingleton::instance()->GetRoot(), "remove_points",
Q_RETURN_ARG(QVariant, returnedValue));
}
void QmlConnector::SendToQmlFuncAddPoints(QVariantList input_one, QVariantList input_two)
{
QVariant returnedValue;
QMetaObject::invokeMethod(QmlMapSingleton::instance()->GetRoot(), "add_points",
Q_RETURN_ARG(QVariant, returnedValue),
Q_ARG(QVariant, QVariant::fromValue(input_one)), Q_ARG(QVariant, QVariant::fromValue(input_two)));
}
.
///-------------- Map.qml -----------------///
Map {
anchors.fill: parent
property variant points: ({})
property int pointCounter: 0
Plugin
{
id: osmplugin
name: "osm"
PluginParameter { name: "osm.mapping.highdpi_tiles"; value: true }
}
Component.onCompleted: {
points = new Array();
}
id: map
plugin: osmplugin
//Javascript functions
function add_points(array_lat, array_lon) {
var myArray = new Array()
var component = Qt.createComponent("mapcircle.qml");
for (var i=0; i<array_lat.length; i++)
{
var object = component.createObject(map, { "center": QtPositioning.coordinate(array_lat[i], array_lon[i]})
map.addMapItem(object)
myArray.push(object)
}
map.points = myArray
}
function remove_points() {
var count = map.points.length
for (var i = 0; i<count; i++){
map.removeMapItem(map.points[i])
map.points[i].destroy()
}
map.points = []
}
}
.
///-------------- mapcircle.qml -----------------///
import QtQuick 2.0
import QtLocation 5.6
MapCircle {
radius: 1
border.width: 0
color: 'green'
}
Qt says that the performance decreases with the number of elements added to the map. Do you need all the points to be visible on the map in the same time, if not you can play around with visibility.
Can't you use QQuickPaintedItem to paint the points in C++ and wrap it into an MapQuickItem, if you have multiple polygonsfor e.g? But also there are some limitation, you cannot have to big images displayed.
If you need all the points maybe you can have different points based on the map zoom level and reduce the number of points added to the map at small zoom level, as was recommended on the other group ...

Ember context passed to a view

I'm trying to figure out what's wrong about sending action from parentView to one of its children view:
I've made a PhotoUploadView used to resize and then upload images; it adds canvas drawing the resized image in a div inside its template:
<div class="img-list">
//here the canvas will be added
</div>
The action "saveImages" in this view, acts like this:
var list = this.$('.img-list');
$.each(list.children(), function(index, value) {
//here the code to save
}
But this action is not called directly; because I need to save not only the images but also some records (an offer record and many products records, children of the offer; the images are associated to the product record);
So I have the action "save" on the parentView that is like this:
//save records
offer.save().then(function(savedOffer) {
newProducts.forEach(function(product, indexP) {
product.set('offer', savedOffer);
product.save().then(function(savedProduct) {
}
}
}
//save photos by cycling the PhotoUploadViews that are inside ProductViews that are inside the mainView
this.get('childViews').forEach(function(view, index) {
if (index >= 4) { //the childView from the 4th are the ProductViews
var productId = view.get('product').get('id');
var folder = 'offer-' + controller.get('model').get('id') + '/product-' + productId + '/';
view.get('childViews')[0].send('saveImages', folder, productId); //the first childView of a ProductView is the UploadView
}
});
Well, this works and save the images correctly when you add images to an existing offer with existing product; but when you are creating a new offer, it fails since the folder will becone "offer-undefined/product-undefined" because of course you must wait the records to be saved in order to get their ID;
So I'm trying now to move the send action into the .then callback of product save:
var childViews = this.get('childViews'); //the childView starting from the 4th are the productsViews
offer.save().then(function(savedOffer) {
newProducts.forEach(function(product, indexP) {
product.set('offer', savedOffer);
product.save().then(function(savedProduct) {
var currentPview = (childViews[4 + indexP]); //get the productView associated with the current product
var productId = savedProduct.get('id');
var folder = 'offer-' + savedOffer.get('id') + '/product-' + productId + '/';
currentPview.get('_childViews')[2].send('saveImages', folder, productId); //the object at index 2 of _childViews array is the photoUploadView
Here, the folder is built correctly but after sending action, the saveImages action crashes saying that list is undefined; trying to log the value of "this" inside "saveImages" I can see that also its value is undefined; Someone can please explain why calling the action from one point, it works, and calling it inside the .then callback of product save it doesn't?
I also would like to understand why in the first case I can do
.get('childViews')[0]
to get the PhotoUploadView, but in the second I must do
.get('_childViews')[2]
since using get('childViews) it doesn't work anymore; What is the difference between childViews and _childViews? And why _childViews has more elements than childView?

Set a variable as the ID of a clicked div, then modify that variable to select a different div

I have multiple images and when I click on one I want the code to set that specific images ID ("image_select_1") as a variable. I then want to modify that variable by removing the text "select" (with underscores on either side of it) from the middle of it so the variable becomes "image1". Then use that variable to target a different DIV and fade it in. Here the is the code I have however it's of course, not working.
var foo;
$('.game_selection_image').click(function() {
foo = $(this).attr("id");
foo = foo.replace("_select_","");
$("#" + foo).fadeIn(500);
});
Any help would be greatly appreciated, thank you :)
Watch your variables
$("div.game_selection_image").click(function(e) {
var foo = $(this).attr("id");
foo = foo.replace("_select_","");
$('#' + foo).fadeIn(500);
});

How do I refresh a TMS layer in OpenLayers?

I have a TMS layer that looks something like this:
var v = 1;
my_tms = new OpenLayers.Layer.TMS(
"My TMS",
"my_mapserver.php?v="+my_var+"&",
{ transparent: 'true', type:'png', getURL:get_my_url }
);
Where my_mapserver.php returns map tiles according to the value of v.
The app allows users to change v, and I simply want to refresh the my_tms layer, however, so far the only way I can get it to refresh is by destroying the map and recreating it.
I thought I could just do something like this:
v = 2;
my_tms = new OpenLayers.Layer.TMS(
"My TMS",
"my_mapserver.php?v="+my_var+"&",
{ transparent: 'true', type:'png', getURL:get_my_url }
);
my_tms.redraw();
However, these tiles are not getting requested when I redraw().
Any help is appreciated.
As TMS layers inherits from Grid layer you could try to call clearGrid() method to remove all existing tiles and then spiralTileLoad() to load new ones.
layer.redraw();, OpenLayers.Strategy.Refresh and clearGrid() didn't help me in reloading tiles of OpenLayers.Layer.TMS layer in OpenLayers 2.13.1, but helped:
layer.mergeNewParams({});