object passing between windows - with write access
Hi all,
i just don't get it. I've two windows - I'll hold the data in window1, pass it to window2, modify it there and want to have this changes in window1 too…
window1:
var window1 = Titanium.UI.currentWindow;
var test = 1;
var window2 = Titanium.UI.createWindow({
backgroundColor:'#cccccc',
title:'Add Note',
url:'window2.js'
});
window2.test = test;
addButton.addEventListener('click', function()
{
window2.open({modal:true});
}
Titanium.App.addEventListener('test', function() {
Ti.API.info('test: ' + test);
});
window2:
saveButton.addEventListener('click', function()
{
Titanium.UI.currentWindow.test = 2;
Titanium.App.fireEvent('test');
addNoteWindow.close();
}
The debug output in window1 is still "test: 1". What's going on here? Shouldn't it be just a reference to the original variable in window1?
Thanks!
3 Answers
-
The problem is your expectation regarding this line:
window2.test = test;
This assigns the value of
test
(which is 1) towindow2.test
.It does not assign a reference or a pointer or anything like that, so the original
test
variable never changes.If you want to modify a value in window1 from window2, you can pass the new value through your custom event in window2:
saveButton.addEventListener('click', function() { Titanium.UI.currentWindow.test = 2; Titanium.App.fireEvent('test', { value:2 }); addNoteWindow.close(); }
See
custom_events.js
in conjunction withapp.js
for an example. -
Thanks James for the clarification!
Then I've got Jeff wrong when he speaks about live references : assing-objects-to-other-windows ?
-
Thanks for linking to Jeff's post. I think it's correct, but the use of the words 'live references' could potentially give rise to some confusion.
I think what he meant was that the properties of window2 can still be accessed in window1 and will be updated in real time as they are changed in window2.
The original
test
variable never changes in either window, butwindow2.test
does change when your button is clicked.So, e.g., you could change your event listener to this:
Titanium.App.addEventListener('test', function() { Ti.API.info('test: ' + window2.test); });
which refers to
window2.test
(changed in window2) instead oftest
(not changed).