언어 설정

Menu
Sites
Language
Tizen Wearable - Best way to pass data between pages

Greetings.

Let's say I have an application that consists of several pages, which are switched by anchor tags (<a href="page.html">).

Which would be the best way to pass data back and forth between the pages? For example, a button should open a list of things to choose from and that list should return back the index of the chosen item.

I've tried using GET-parameters, and they sort of work, you can parse them manually from 'location.search' global variable, but it seems messy, especially when returning values back.

Could there be a better solution to this?

Thanks in advance.

답변 바로가기

Responses

6 댓글
Stephan König

Hi Nate,

you should have a look into the sample applications, e.g. the stopwatch.
They contain the tau.js lib and also some predefined js core in /js/core. This stuff provides some requirejs functions.

If you use this structure you will need only one .html file and you can trigger page changes by js events.
In this events you pass data in JSON as a parameter.

Example:

on first page trigger a page change and pass data as param:

e.fire('page2.show', {"mydata": {"key1": 123, "foo": "bar"}});

on second page recive event in callback:

 function show(ev) {
    var mydata = ev.detail;
    var foo = mydata.foo;
 }

 

There also some more events beside show, like "pageshow", "pagebeforeshow", "pagehide" ...

 

Regards
 

Nate River

Yeah, I've seen this sample app, however I didn't pay much attention to it because there is no tutorials or documentation for the library it uses. Yes, its source code is well documented, but it's hard to get grips with it only by studying its source code. It would took ages. I've event tried running it through JSDoc but it gave miserable results because as I assume not all documentation follows its standards.

So is there an already generated documentation somewhere? That would be awesome.

 

Stephan König

Yes, you're right, there is no documentation for tau.js yet :(
We have done a lot of try and error with this, but http://requirejs.org/docs/start.html may provide some usefull informations about the structure they for the core stuff.

I think depending on what you are planing to do you can also use jquery mobile instead of the tau.js stuff. There you have a super documentaion and good examples.

Regards

Marco Buettner

You can use a global variable (tmpData) or webStorage (localStorage or sessionStorage)...

var tmpData = null,
    page2 = document.querySelector("#page2");
    button = document.querySelector("div.ui-page-active a[name=mybutton]");

/* [...] */

button.addEventListener("click", function(evt) {
    tmpData = {"mydata":{"user":"xyz","time":2132342422}};
    //localStorage("tmpdata", JSON.stringify(tmpData)); // save as string, permenant
    //sessionStorage("tmpdata", JSON.stringify(tmpData)); // save as string, until app closed

    tau.changePage("#page2");
});

/* on page 2 */
page2.addEventListener("pagebeforeshow", function(evt) {
    var data = tmpData;
    //var data = JSON.parse(localStorage("tmpdata")); // transform from string to object
    //var data = JSON.parse(sessionStorage("tmpdata")); // transform from string to object

    /* TODO: Do something with your tmpData */
});

 

Mark as answer
Nate River

Ok, so at the end of the day I came up with the following solution, combining some features of the other ones:

document.addEventListener('click', function(e) {
    e = e || window.event;
    var target = e.target || e.srcElement;
    
    while (target != this) {
        if (target.nodeName === 'A') {
            var href = target.getAttribute('href');
            //href should be a page ID, so nothing other than one hash and letters is allowed
            if (href.match(/^#[a-zA-Z]{1}\w*$/) !== null) {
                //now test if element with this ID is an .ui-page
                var page = document.querySelector(href);
                if (page.classList.contains('ui-page')) {
                    //now we can safely change page
                    showPage(page, target.dataset);

                    e.preventDefault();
                    e.cancelBubble=true;
                    e.stopPropagation();
                    return false;
                }
                break;
            }
            break;
        }
        target = target.parentNode;
    }
    return;
    
}, false);

function showPage(page_id, ev) {
	var event = new CustomEvent('pagechange', { 'detail': ev });
	if (typeof page_id !== 'object') {
		page_id = page_id.replace(/#+/, '');
		page_id = document.querySelector('.ui-page#'+page_id);
	}
	if (page_id && typeof page_id === 'object' && page_id.dispatchEvent !== undefined) {
        if (page_id.dataset.script !== undefined) {
            //load script for this page
            var head = document.getElementsByTagName('head')[0],
                script = document.createElement('script');

            script.type = 'text/javascript';
            script.src = page_id.dataset.script;

            script.onreadystatechange = script.onload = function () {
                page_id.dispatchEvent(event);
                tau.changePage(page_id);
            };
            
            head.appendChild(script);
        } else {
            page_id.dispatchEvent(event);
            tau.changePage(page_id);    
        }
	}
}

This code doesn't require manual execution, you just put <a href="#page_id_to_switch_to"> on your page and it gets handled automatically via document click listener. If you want to pass data to page initialization, you can add it with data-* attributes, for example:

<a href="#list_page" data-category="2" data-show-deprecated="true">

To process data on page switch you should add handler for 'pagechange' event, for example:

page_object.addEventListener("pagechange", function (e) {
    console.log('received data:');
    console.log(e.details);
});

'e.details' will contain an associative array of all data-* attributes that were present in anchor tag. Note here: 'data-field' will turn to 'e.details.field' and 'data-field-text' will turn to 'e.details.fieldText', e.g. complex data-* attribute names are turned into CamelCase fields.

This approach allows to separate all application pages into different *.html files and use separate *.js files for them as well. However, if you want to have source code for another page in a separate *.js file, you'll need to add 'data-script' attribute with URL of your *.js file to '.ui-page' element of that page. It will be loaded and executed before 'pagechange' event will be dispatched, so you can add handler for it in that very *.js file and don't clutter main application *.js file.

Nate River

Oh, I forgot to mention that TAU built-in event 'pagebeforeshow' is triggered AFTER 'pagechanged', so that you can store received data in 'pagechanged' and use it later to build UI in 'pagebeforeshow'.

This is done so because you can't pass custom data to built-in events, that would require altering TAU framework itself.