user3996249
user3996249

Reputation:

Give text from function to view in titanium

I have a small question about titanium. What i am trying to do is pass text from my function to a label on my view. Can someone explain to me how i can accomplish this. The function is in an other file then the label.

Im trying to do this: text from function --> label

This is my code:

//making the milking view
var milkingView = Ti.UI.createView({
    backgroundColor: 'white'
});

var title = new Ti.UI.createLabel({
    top: 20,
    left: per25,
    height: 30,
    text: 'MilkingResults:',
    color: 'black',
    font: {fontSize: 18}
});

var text = new Ti.UI.createLabel({
    top: 20,
    left: per25,
    height: 30,
    text: 'here i want the text from the function',
    color: 'black',
    font: {fontSize: 18}
});

The above is the code for the view, down below is the code for the function

function http_get(subpage) {
     var url = "url" + subpage;
 var http_client = Ti.Network.createHTTPClient({
     // function called when the response data is available
     onload : function(e) {
         Ti.API.info("Received text: " + this.responseText);
         alert('success');
     },
     // function called when an error occurs, including a timeout
     onerror : function(e) {
         Ti.API.debug(e.error);
         alert('error');
     },
     timeout : 5000  // in milliseconds
 });
 // Prepare the connection.
 http_client.open("GET", url);
 // Send the request.
 http_client.send();  

};

Thanks in advance

Upvotes: 1

Views: 43

Answers (1)

Olivier
Olivier

Reputation: 921

The challenge is that the http_client.onload function is async. One thing you can do is pass a callback at your http_get function.

For example, in your first file, you can have the following function:

function updateLabel(textFromOnLoad){
    text.text = textFromOnLoad;
};

and modify your http_get that way:

function http_get(subpage, callback) {
     var url = "url" + subpage;
 var http_client = Ti.Network.createHTTPClient({
     // function called when the response data is available
     onload : function(e) {
         callback(this.responseText);
     },
     // function called when an error occurs, including a timeout
     onerror : function(e) {
         Ti.API.debug(e.error);
         alert('error');
     },
     timeout : 5000  // in milliseconds
 });
 // Prepare the connection.
 http_client.open("GET", url);
 // Send the request.
 http_client.send();  

};

Then you can call in your first file:

http_get(subpage,updateLabel);

Upvotes: 1

Related Questions