Open new window from TableView in Titanium Mobile - javascript

i create some application in titanium mobile for opening a window when a row in TableView is clicked by user..
here's my code:
Menu.js
function Menu() {
Titanium.UI.setBackgroundColor('#000');
var masterMenu = Titanium.UI.createTabGroup();
var winMenu1 = Titanium.UI.createWindow({
title:'Menu 1',
backgroundColor:'#fff'
});
var tabMenu1 = Titanium.UI.createTab({
icon:'KS_nav_views.png',
title:'Menu 1',
window:winMenu1
});
var menuData1 = [
{title: 'Account', url: 'Account.js'},
{title: 'Meetings', url: 'Meetings.js'}
];
var menuList1 = Ti.UI.createTableView({
data: menuData1
});
menuList1.addEventListener('click', function(e) {
var newWindow = Titanium.UI.createWindow({
url:e.rowData.url,
title:e.rowData.title
});
newWindow.open({
animated:true
});
});
winMenu1.add(menuList1);
var winMenu2 = Titanium.UI.createWindow({
title:'Menu 2',
backgroundColor:'#fff'
});
var tabMenu2 = Titanium.UI.createTab({
icon:'KS_nav_ui.png',
title:'Menu 2',
window:winMenu2
});
masterMenu.addTab(tabMenu1);
masterMenu.addTab(tabMenu2);
return masterMenu;
}
module.exports = Menu;
when some row is clicked by user, it will redirect and open new window based on url on the menuData1. for example i clicked Account row, and it should be redirected to Account.js. Here's my Account.js code :
var win = Ti.UI.currentWindow;
var label1 = Titanium.UI.createLabel({
color:'#999',
text:'Close',
font:{fontSize:20,fontFamily:'Helvetica Neue'},
textAlign:'center',
width:'auto'
});
label1.addEventListener('click', function() {
win.close();
});
win.add(label1);
The main problem is label1 in Account.js not opened in new window but shown in menu list.
Does anyone know how to open Account.js in new window?? thanks before..

Try to set backgroundColor for your window:
menuList1.addEventListener('click', function(e) {
var newWindow = Titanium.UI.createWindow({
backgroundColor: '#fff',
url:e.rowData.url,
title:e.rowData.title
});
newWindow.open({
animated:true
});
});

Related

backbone drag and drop - getting dropped data

I'm relatively new to programming and this is my first time posting on here, so sorry in advance if this isn't presented correctly.
I'm building a health tracker app with Backbone JS. I am retrieving data from the Nutritionix API and populating a view on the left side of the screen with that data. I want the user to be able to drag an item from the populated view and drop it in a view to the right in which case a calorie counter will increase. I also need that data to persist so that when the user closes and reopens the app their selected data in the view will remain the same.
I've implemented the drag and drop feature just fine. I am now trying to make it so that when the user drops an item from the left view into the right view a collection is created that only contains the data in the right view. I believe that I need to do this so I can persist the data. Right now, I am having trouble transferring the API data along into the right view. Here are the relevant code snippets:
appView:
var app = app || {};
var ENTER_KEY = 13;
app.AppView = Backbone.View.extend({
el: '#health-app',
urlRoot: 'https://api.nutritionix.com/v1_1/search/',
events: {
'keypress': 'search',
'click #clearBtn': 'clearFoodList',
'drop .drop-area': 'addSelectedFood',
// 'drop #selected-food-template': 'addSelectedFood'
},
initialize: function() {
this.listenTo(app.ResultCollection, 'add', this.addFoodResult);
// this.listenTo(app.SelectedCollection, 'add', this.addSelectedFood);
app.ResultCollection.fetch();
app.SelectedCollection.fetch();
this.clearFoodList()
},
addFoodResult: function(resultFood) {
var foodResult = new SearchResultView({
model: resultFood
});
$('#list').append(foodResult.render().el);
},
// addSelectedFood: function(selectedFood) {
// // var selectedFoodCollection = app.SelectedCollection.add(selectedFood)
// console.log(app.SelectedCollection.add(selectedFood))
// },
clearFoodList: function() {
_.invoke(app.ResultCollection.toArray(), 'destroy');
$('#list').empty();
return false;
},
search: function(e) {
var food;
//When the user searches, clear the list
if($('#search').val() === '') {
_.invoke(app.ResultCollection.toArray(), 'destroy');
$('#list').empty();
}
//Get the nutrition information, and add to app.FoodModel
if (e.which === ENTER_KEY) {
this.query = $('#search').val() + '?fields=item_name%2Citem_id%2Cbrand_name%2Cnf_calories%2Cnf_total_fat&appId=be7425dc&appKey=c7abd4497e5d3c8a1358fb6da9ec1afe';
this.newUrl = this.urlRoot + this.query;
var getFood = $.get(this.newUrl, function(data) {
var hits = data.hits;
var name, brand_name, calories, id;
_.each(hits, function(hit){
name = hit.fields.item_name;
brand_name = hit.fields.brand_name;
calories = hit.fields.nf_calories;
id = hit.fields.item_id;
food = new app.FoodModel({
name: name,
brand_name: brand_name,
calories: calories,
id: id
});
//If the food isn't in the ResultCollection, add it.
if (!app.ResultCollection.contains(food)) {
app.ResultCollection.add(food);
}
});
food.save();
});
}
}
});
breakfastView:
var app = app || {};
app.BreakfastView = Backbone.View.extend({
el: '#breakfast',
attributes: {
'ondrop': 'ev.dataTransfer.getData("text")',
'ondragover': 'allowDrop(event)'
},
events: {
'dragenter': 'dragEnter',
'dragover': 'dragOver',
'drop': 'dropped'
},
initialize: function() {
this.listenTo(app.SelectedCollection, 'change', this.addSelectedFood);
},
render: function() {},
addSelectedFood: function(selectedFood) {
// var selectedFoodCollection = app.SelectedCollection.add(selectedFood)
console.log(app.SelectedCollection.add(selectedFood))
},
dragEnter: function (e) {
e.preventDefault();
},
dragOver: function(e) {
e.preventDefault();
},
dropped: function(ev) {
var data = ev.originalEvent.dataTransfer.getData("text/plain");
ev.target.appendChild(document.getElementById(data));
// console.log(app.SelectedCollection)
this.addSelectedFood(data);
},
});
new app.BreakfastView
SelectedCollection:
var app = app || {};
app.SelectedCollection = Backbone.Collection.extend({
model: app.FoodModel,
localStorage: new Backbone.LocalStorage('selected-food'),
})
app.SelectedCollection = new app.SelectedCollection();
Here's my repo also, just in case: https://github.com/jawaka72/health-tracker-app/tree/master/js
Thank you very much for any help!

XMLHttpRequest in Firefox on websites meta information

I am new to Firexfox Add-On development and I would like to parse meta-tags from a website in the internet. My Firefox Add-On development environment is setup completely and a panel in the toolbar appears as it should be. When I open the panel the current visited website should be read by its meta-tags. In the following you will see amazon.de as example.
This is how my main.js file looks like:
var { ToggleButton } = require('sdk/ui/button/toggle');
var panels = require("sdk/panel");
var self = require("sdk/self");
var button = ToggleButton({
id: "my-button",
label: "my button",
icon: {
"16": "./icon-16.png",
"32": "./icon-32.png",
"64": "./icon-64.png"
},
onChange: handleChange
});
var panel = panels.Panel({
contentURL: self.data.url("panel.html"),
onHide: handleHide
});
function handleChange(state) {
if (state.checked) {
panel.show({
position: button
});
}
}
function handleHide() {
button.state('window', {checked: false});
}
And this is the panel where the current visited website should be read by its meta-tags:
<script>
// https://developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript
var req = new XMLHttpRequest();
req.open("GET", "http://www.amazon.de/Apple-Smartphone-Retina-Display-Megapixel-Bluetooth/dp/B00F8JF2OM/", false);
req.send(null);
var xmlDoc = req.responseXML;
var nsResolver = xmlDoc.createNSResolver( xmlDoc.ownerDocument == null ? xmlDoc.documentElement : xmlDoc.ownerDocument.documentElement);
//XPath 'html//meta[#name="title"]/#content'
var itemIterator = xmlDoc.evaluate('html//meta[#name="title"]/#content', xmlDoc, nsResolver, XPathResult.ANY_TYPE, null );
var thisHeading = itemIterator.iterateNext();
var alertText = 'Items:\n'
while (thisHeading) {
alertText += thisHeading.textContent + '\n';
thisHeading = itemIterator.iterateNext();
}
</script>
I don't get any errors and don't get any alert or output data.
However the Firfox XPath add-on tells me the path is correct and shows the data.

Clearing last JSON response

I am developing an iOS 6.1 app using Titanium Studio, build: 3.1.2.201307091805, I am testing on the iPhone simulator and iPad device. I have a search field that gets JSON results from a remote server. The screen I am having issues with has the search box at the top and a couple of messages below. When the user types in the search field and hits return, the messages are hidden and a table is placed ready to receive the results from the database. All of that is working fine. When the user types in something that is not in the database I have a message appear "No results found, please try again". I made a button to "Clear" the table or "Not Found" message. Here is the button code I have so far:
var clear = Ti.UI.createButton({
title: "Clear",
style:Titanium.UI.iPhone.SystemButtonStyle.BORDERED
});
clear.addEventListener("click", function() {
message.hide();
table.setData([]);
});
Ti.UI.currentWindow.setRightNavButton(clear);
This code does clear the message or the results in the table but when I do another search the previous result appears above the new result even if the searches were totally unrelated. Here is my code.
var win = Titanium.UI.currentWindow;
win.backgroundImage='images/background.png';
win.barColor='#28517A';
win.title='Product Search';
var message = Ti.UI.createLabel({
text: 'No results found, please try again',
top:'100dp',
left:'20dp',
right:'20dp'
});
var customSearchBar = Ti.UI.createView({
backgroundColor: '#28517A',
height: 42,
top: '0dp',
width: Ti.UI.FILL
});
var customSearchField = Ti.UI.createTextField({
autocorrect: false,
borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
clearOnEdit: true,
height: 28,
hintText: 'Search For Product or Service',
textAlign: 'center',
width: '90%',
});
customSearchBar.add(customSearchField);
win.add(customSearchBar);
var nolist= Ti.UI.createLabel({
text: 'XXXXXX',
color: '#000',
font: {fontSize:'16dp', fontWeight:'bold'},
top:'50dp',
left:'20dp',
right:'20dp'
});
win.add(nolist);
var businessowner = Ti.UI.createLabel({
text: 'XXXXXX',
color: '#000',
font: {fontSize:'16dp', fontWeight:'bold'},
bottom:'10dp',
left:'20dp',
right:'20dp'
});
win.add(businessowner);
var view = Ti.UI.createView({
backgroundColor: 'transparent',
top: '100dp',
bottom:'60dp'
});
var table = Ti.UI.createTableView({
backgroundColor: 'transparent',
top: '0dp',
height:'auto',
bottom:'0dp'
});
view.add(table);
table.show();
var tableData = [];
function checkInternetConnection(){
return Ti.Network.online ? true : false;
}
customSearchField.addEventListener("return", function(e) {
if(checkInternetConnection()){
nolist.hide();
businessowner.hide();
getdata();
win.add(view);
function getdata(){
var url = "http://mydomain.com/filename.php?title="+e.value;
var xhr = Ti.Network.createHTTPClient({
onload: function() {
Ti.API.debug(this.responseText);
var json = JSON.parse(this.responseText);
if (json.cms_list.length< 1){
win.add(message);
}
for (i = 0; i < json.cms_list.length; i++) {
client = json.cms_list[i];
row = Ti.UI.createTableViewRow({
height:'44dp',
hasChild:true
});
var clientlist = Ti.UI.createLabel({
text:client.clientname,
font:{fontSize:'16dp', fontWeight:'bold'},
height:'auto',
left:'10dp',
color:'#000'
});
row.add(clientlist);
tableData.push(row);
}
table.addEventListener('click',function(e){
var row = e.row;
var clientlist = row.children[0];
var win = Ti.UI.createWindow({
url: 'clientdetail.js',
title: clientlist.text
});
var clientlist = clientlist.text;
win.clientlist = clientlist;
customSearchField.blur();
Titanium.UI.currentTab.open(win,{animated:true});});
table.setData(tableData);
},
onerror: function(e) {
Ti.API.debug("STATUS: " + this.status);
Ti.API.debug("TEXT: " + this.responseText);
Ti.API.debug("ERROR: " + e.error);
alert('There was an error retrieving the remote data. Try again.');
},
timeout:5000
});
xhr.open("GET", url);
xhr.send();
}
}
else{
alert('Your internet connection is not available');
}
});
var clear = Ti.UI.createButton({
title: "Clear",
style:Titanium.UI.iPhone.SystemButtonStyle.BORDERED
});
clear.addEventListener("click", function() {
message.hide();
table.setData([]);
});
Ti.UI.currentWindow.setRightNavButton(clear);
If I press my back button and then return to this screen, the search is fine. How can I completely clear the previous results without leaving the screen and then returning?
You are adding the table to the window every time you click "return". Change your event listener by removing win.add(view); from it, and replace that line with table.show(); like this:
customSearchField.addEventListener("return", function(e) {
if(checkInternetConnection()){
nolist.hide();
businessowner.hide();
getdata();
//win.add(view); dont do this!!!!
table.show();
.....
});
Then, change this:
var table = Ti.UI.createTableView({
backgroundColor: 'transparent',
top: '0dp',
height:'auto',
bottom:'0dp'
});
view.add(table);
//table.show();
win.add(table);
table.hide();
Now you will only have one instance of a table, and you can use setData inside the return listener every time you want to change all the rows.
You are not clearing data from var tabledata. It should be cleared when you are setting table.setData([]); . It is pushing the same data after setting the table as empty.
Your code should look like this:
clear.addEventListener("click", function() {
message.hide();
tableData = [];
table.setData([]);
});

How to close modal window from other JS file on titanium mobile?

i create this simple login App in titanium mobile.. here's my code :
Login.js
function Login() {
var loginView = Titanium.UI.createView({
backgroundColor:'#C4FBFF',
layout:'vertical'
});
var txtUsername = Titanium.UI.createTextField({
width:'75%',
hintText:'Username',
borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED
});
var txtPassword = Titanium.UI.createTextField({
width:'75%',
hintText:'Password',
borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED,
passwordMask:true
});
var btnLogin = Titanium.UI.createButton({
title:'Login',
width:'75%'
});
loginView.add(txtUsername);
loginView.add(txtPassword);
loginView.add(btnLogin);
btnLogin.addEventListener('click',function(e){
var alertDialog = Titanium.UI.createAlertDialog({
title: 'Confirmation',
message: 'You will be logged in as ' + txtUsername.value + ', continue?',
buttonNames: ['Yes','No']
});
alertDialog.addEventListener('click',function(e){
if (e.index === 0){ //Yes Pressed
var MainMenu = require('ui/common/MainMenu');
var mainMenuWindow = Titanium.UI.createWindow({
backgroundColor:'#336699',
title:'Main Menu',
modal:true
});
var mainMenu = new MainMenu();
mainMenuWindow.add(mainMenu);
mainMenuWindow.open();
}
else{ // No Pressed
makeAlert('Login','Please contact your system administrator');
}
});
alertDialog.show();
});
function makeAlert(title, message) {
var customAlertDialog = Titanium.UI.createAlertDialog({
title: title,
message: message,
buttonNames: ['Ok']
});
return customAlertDialog.show();
}
return loginView;
}
module.exports = Login;
and this is my MainMenu.js :
function MainMenu(){
var mainMenuView = Titanium.UI.createView({
backgroundColor:'#C4FBFF',
layout:'vertical'
});
var btnClose = Titanium.UI.createButton({
title:'Close',
height:30,
width:150
});
mainMenuView.add(btnClose);
btnClose.addEventListener('click',function(e){
//What should i do here?
});
return mainMenuView;
}
module.exports = MainMenu;
The main problem is i want to close modal window when close button is pressed. i've tried Titanium.UI.currentWindow.close() but it close all my application and it can't be executed on iOS devices. any suggestion?? many thanks..
// pass parent window in as parameter
var mainMenu = new MainMenu(mainMenuWindow);
mainMenuWindow.add(mainMenu);
now use the parameter
function MainMenu(_parent /*parent window*/){
// other code ...
btnClose.addEventListener('click',function(e){
_parent.close();
});
}

Using Titanium, Remove current view or pop current view

I have to remove current view being in the same view...
if i am in the parent view i can do
parentView.remove(childView);
but being on the child view i am not having parentView so how can i pop childView to get parentView on top, as it happens on pressing the back button in iOS??
please help
Here is my childView file..
function DetailView(){
var self = Ti.UI.createView({
backgroundColor:'#fff'
});
// Create a Button.
var aButton = Ti.UI.createButton({
title : 'aButton',
height : '50',
width : '100',
top : '10',
left : '20'
});
// Listen for click events.
aButton.addEventListener('click', function() {
alert('\'aButton\' was clicked!');
I have to navigate back on press of aButton, what should i Put here to do that
});
// Add to the parent view.
self.add(aButton);
return(self);
}
module.exports = DetailView;
Here is my parent view:
//FirstView Component Constructor
var self = Ti.UI.createView();
function FirstView() {
//create object instance, a parasitic subclass of Observable
var DetailView = require('ui/common/DetailView');
var data = [{title:"Row 1"},{title:"Row 2"}];
var table = Titanium.UI.createTableView({
data:data
});
table.addEventListener('click', rowSelected);
self.add(table);
return self;
}
function rowSelected()
{
var DetailView = require('ui/common/DetailView');
//construct UI
var detailView = new DetailView();
self.add(detailView);
}
module.exports = FirstView;
You can pass your parentView to the constructor of child view at this point:
//construct UI
var detailView = new DetailView(parentView);
self.add(detailView);
and in click event
aButton.addEventListener('click', function() {
if ( parentView != null ) {
parentView.remove(childView);
}
});

Categories