Really a javascript question, but here's my code........I would truly appreciate some help. Been too long since I've been in the coding trenches. Here's my code.
I want to make loadtravelurl into a single function I can call from multiple places.
These three lines below are my issues.
win2.title = title;
win2.add(tv);
tab2.open(webwin);
I want to be able to pass variables in loadelectronicsurl function, where I can change the text win2 in win2.title and win2.add(tv) dynamically. Also want to do the same with tab2. I know it can be done, just had a few years off and forgot how to do so in javascript.
Here is the full code, thanks so much for the help in advance!
function loadelectronicsurl(){
var WindowWidth = Ti.Platform.displayCaps.platformWidth;
var WindowHeight = Ti.Platform.displayCaps.platformHeight;
var xhr = Titanium.Network.createHTTPClient();
xhr.open('GET',electronicsurl);
var data = [];
var WindowWidth = Ti.Platform.displayCaps.platformWidth;
xhr.onload = function() {
//Ti.API.info(this.responseText);
var xml = this.responseXML;
var channel = xml.documentElement.getElementsByTagName("channel");
var title = channel.item(0).getElementsByTagName("title").item(0).text;
win2.title = title;
var items = xml.documentElement.getElementsByTagName("item");
for (var i=0;i<items.length;i++) {
var this_post_title = items.item(i).getElementsByTagName("title").item(0).text;
var post_link = items.item(i).getElementsByTagName("link").item(0).text;
var row = Ti.UI.createTableViewRow({height:'auto',width:WindowWidth,top:0,hasChild: false});
var post_title = Ti.UI.createLabel({
text: this_post_title,
textAlign:'left',
left:0,
height:40,
font:{fontFamily:'Arial',fontSize:12},
width:'auto',
top:3,
color: 'black'
});
row.add(post_title);
row.link = post_link;
data.push(row);
}
var tv = Titanium.UI.createTableView({
data:data,
top:0,
width:WindowWidth,
height:WindowHeight
});
win2.add(tv);
tv.addEventListener('click',function(e) {
var webwin = Titanium.UI.createWindow({
url: 'showweb.js',
backgroundColor: '#fff',
myurl: e.rowData.link
});
tab2.open(webwin);
});
};
xhr.send();
}
You can define parameters for a function like this:
function someFunc(win, tab){
win.add();
tab.open();
}
You can also use the parameters to access properties of an object dynamically like this:
function someFunc(win, tab){
obj.[win](); //To call an object's method
obj.[tab]; //To access an object's property
}
Call the function and pass the paramters:
someFunc(someObject, anotherObject);
someObject becomes win and anotherObject becomes tab inside the function.
Related
I am working on small api to get content from my database. I want to show data in a JavaScript/jQuery function according to variables I declared.
example
<script>
function dataset() {
var url = "www.example.com";
var name = "Mini Api";
ver version = "1.00";
this.return url;
this.return name;
this.return version;
}
</script>
How I intend to use it
<script>
minapi = new dataset();
//here I want to return only name
alert(minapi.name);
</script>
Please any idea of how to get this done?
In addition, is there a way to create jQuery function to execute once page load without using this $( document ).ready(function() {});?
I think you want this:
function dataset() {
var myData = {
url: "www.example.com",
name: "mini api",
version: "1.00"
};
return myData;
}
var myVar = dataset();
console.log(myVar.name);
JSFiddle: https://jsfiddle.net/1455d5z3/
This is what you are attempting to do. I fixed ver and assigned properties correctly.
function dataset() {
var url = "www.example.com";
var name = "Mini Api";
var version = "1.00";
this.url = url;
this.name = name;
this.version = version;
}
There might be better ways to do this depending on your situation, but this does give the result you want.
Please use like this.
function dataset() {
var url = "www.example.com";
var name = "Mini Api";
var version = "1.00";
this.returnUrl = function (){
return url;
}
this.returnName = function (){
return name;
}
this.returnVersion = function (){
return version;
}
}
var minapi = new dataset();
alert(minapi.returnName());
Refer Fiddle
this is my situation:
I have a Field.js file which contains a bunch of classes (made with this plugin) each corresponding to a datatype on the page.
An example of a class:
$.Class("Types_UserId_Js",{
init_done : false,
validate : function (value){
return true;
}
},{
container : "",
UserIdDisplay : function (){
var associations = [];
var uid = 0;
$( container ).find(".userid_display").each(function(index,el){
uid = $( this ).find(".userid_value").val();
url = siteurl + "/dname?";
$.ajax({
type: "POST",
url: url,
data: ajaxData,
dataType: "json",
success: function(result, status){
associations[uid] = result;
}
});
});
},
init : function ( container ) {
if(container.length > 0 && !Types_UserId_Js.init_done){
this.container = container;
this.UserIdDisplay();
Types_UserId_Js.init_done = true;
}
};
});
(It's a dummy class for now).
I also have some html code that renders the types UI, in a standard format.
In the end, I have a page with a bunch of different types of inputs, and they all need their specific init function to be called in order to render properly.
What I did up to now is simply invoke EVERY init function in the Field.js file, like so:
$( document ).ready(function(ev){
var cont = $("#container");
var uid = new Types_UserId_Js(cont);
var text = new Types_Text_Js(cont);
// And so forth
});
I'd really like to know if there is a more efficient way to call every init function in the file without having to call them individually.
The Field.js is part of the main framework, and it is maintained by a third party developer so, while I can and do edit it to my leisure, I'd prefer to keep the generic structure that they imposed.
Thank you,
I think you'd need some mapping field <-> function. You can add data-attributes to the fields with the name of the fields init function. Then you can just loop over your fields, get the value and execute the function.
Check the following snippet:
// helper function borrowed from http://stackoverflow.com/a/12380392/4410144
var getFunctionFromString = function(string) {
var scope = window;
var scopeSplit = string.split('.');
for (i = 0; i < scopeSplit.length - 1; i++) {
scope = scope[scopeSplit[i]];
if (scope == undefined) return;
}
return scope[scopeSplit[scopeSplit.length - 1]];
}
var myFunction = function() {
console.log('myFunction');
}
var myOtherFunction = function() {
console.log('myOtherFunction');
}
$('input').each(function() {
var initFunction = getFunctionFromString($(this).data('function'));
initFunction();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-function="myFunction" />
<input data-function="myOtherFunction" />
Hi guys This is my code of two javascript.i want to access variable defined in first javascript into another script.
1)
<script>
$(document).ready(function()
{
$('pre.codeguru').each(function()
{
var pre = this;
var form = $('form[name=sample]').clone();
$(form).removeAttr('name');
$(form).removeClass('hidden');
$($(form).find('textarea')[0]).val($(pre).text());
var id = $(pre).attr('id');
$(form).find('div textarea[name=code]').first().attr('id', id);
$(pre).replaceWith(form);
});
var editors = [];
$('textarea[name=codeguru]').each(function()
{
var editor = CodeMirror.fromTextArea(this,
{
lineNumbers: true,
matchBrackets: true,
mode: "application/x-httpd-perl",
tabMode: "shift"
});
editors.push(editor);
});
});
</script>
2)
<script type="text/javascript">
function execute() {
p5pkg.CORE.print = function(List__) {
var i;
for (i = 0; i < List__.length; i++) {
document.getElementById('print-result').value += p5str(List__[i])
}
return true;
};
p5pkg["main"]["v_^O"] = "browser";
p5pkg["main"]["Hash_INC"]["Perlito5/strict.pm"] = "Perlito5/strict.pm";
p5pkg["main"]["Hash_INC"]["Perlito5/warnings.pm"] = "Perlito5/warnings.pm";
var source = editor.getValue();
alert(source);
var pos = 0;
var ast;
var match;
document.getElementById('print-result').value = "";
try {
var start = new Date().getTime();
var js_source = p5pkg["Perlito5"].compile_p5_to_js([source]);
var end = new Date().getTime();
var time = end - start;
// run
start = new Date().getTime();
eval(js_source);
end = new Date().getTime();
time = end - start;
}
catch(err) {
//document.getElementById('log-result').value += "Error:\n";
}
}
</script>
Now my problem is i want to access the editor defined in first javascript as
var editors = [];
$('textarea[name=codeguru]').each(function()
{
var editor = CodeMirror.fromTextArea(this,
{
lineNumbers: true,
matchBrackets: true,
mode: "application/x-httpd-perl",
tabMode: "shift"
});
editors.push(editor);
});
in second javascript.
anyone has answer of this then please help me to do so
If you leave out var while defining variables they will be globally accessible.
So
pre = this;
instead of
var pre = this;
would make pre accessible from every function.
the only way I can think is to pass the variable into the other functions as a variable
function otherJavaFile.myFunction (myVariable);
or alter a variable in the HTML i.e. the custom data-value and then the other script can access it. I don't like global variables.
// Sheet 1
$("#myDiv").attr("data-variable",yourValue);
// Sheet 2
var secondVariable = $("#myDiv").attr("data-variable");
buddy i am not comfortable with jquery...
I hope you are looking forward for the iframes/frames on same document[window sharing].
Based on my knowledge of Javascript DOM to access a variable defined in one document inside another document.You have to use document.importNode(original Node as in other document,boolean) method as per DOM 2.
Do something like this for javacript code ...
documentI(original variable/node present here)- iframe.contentDocument.getElementsByTagName(/Tag name of Node/)...
documentII(node to be cloned here)-
document.importNode(originalNode,True)
I hope this works
I am building a mobile app using Titanium for ios and I am having a tough time getting my arms wrapped around passing variables. I am using a combination of local database and remote database to deliver my data. In this case I want to pass the data on the tableViewRow selected. The label that displays the data I call "categorydescription". In my table.addEventListener, I want to pass that data as the title for the new window and I will pass that same data to my php file on the remote server. Here is the code I am trying to use:
var xhr = Ti.Network.createHTTPClient({
onload: function() {
Ti.API.debug(this.responseText);
var json = JSON.parse(this.responseText);
for (i = 0; i < json.cms_client.length; i++) {
client = json.cms_client[i];
row = Ti.UI.createTableViewRow({
height:'44dp',
hasChild:true
});
var categorydescription = Ti.UI.createLabel({
text:client.catdesc,
font:{fontSize:'16dp', fontWeight:'bold'},
height:'auto',
left:'10dp',
color:'#000'
});
row.add(categorydescription);
tableData.push(row);
}
table.addEventListener('click',function(e) {
var win = Ti.UI.createWindow({url: 'clients.js', title: ??});
var catdesc = ??;
win.catdesc = catdesc;
Titanium.UI.currentTab.open(win,{animated:true});
});
table.setData(tableData);
Would someone be so kind to tell me what I need to put in place of the ?? in the 'title' and 'var catdesc' above?
Just add the category description and title to the row object itself:
row = Ti.UI.createTableViewRow({
height:'44dp',
hasChild:true,
categoryDescription : client.catdesc, //Add this
clientTitle : client.title // Add this
});
Now get them in the listener:
table.addEventListener('click',function(e) {
var win = Ti.UI.createWindow({url: 'clients.js', title: e.row.title});
var catdesc = e.row.categoryDescription;
win.catdesc = catdesc;
Titanium.UI.currentTab.open(win,{animated:true});
});
I am (slowly) writing an XML parser for some "site definition" files that will drive a website. Many of the elements will be parsed in the same manner and I won't necessarily need to keep the values for each.
The XML
The parser so far
My question is actually pretty simple: How can I use jquery manipulators in an class function? How can I pass $(this)? I know that it sometimes refers to a DOM object and sometimes the jQuery object, but am a bit hazy.
For my function:
function parseXML(xml) {
$("book, site", xml).children().each(function() {
var label = $(this).get(0).tagName;
var text = $(this).text();
var key = toCamelCase(label);
if ((key in siteData) && (text != -1)){
if (isArray(siteData[key]))
{
$(this).children().each(function (){
var childLabel = $(this).get(0).tagName;
var childText = $(this).text();
var childKey = toCamelCase(childLabel);
if(isArray(siteData[key][childKey]))
{
siteData[key][childKey].push(childText);
}
else {
siteData[key].push(childText);
}
});
}
else
{
siteData[key] = text;
}
};
});
}
});
I want to place
var label = $(this).get(0).tagName; var text = $(this).text(); var key = toCamelCase(label);
in a class, so I can do something like
var child = new Element(); and var subchild = new Element();
and then use child.label , child.text and child.key...
But again, not sure how to use the jquery methods with these... I have more nodes to process and I don't want to keep doing stuff like var label = $(this).get(0).tagName; and then var childLabel = $(this).get(0).tagName;
Thanks.
var app = {};
app.element = function(data) {
return function() {
var _text = data.get(0).tagName, _label= data.text(), _key = toCamelCase(_label);
var that = {};
that.label = function() {
return _label;
}
that.text = function() {
return _text;
}
that.key = function() {
return _key;
}
return that;
}();
};
app.instanceA = app.element($(this));
document.writeln(app.instanceA.label());
Ok so this works but, I'm not sure if it's the best way.