开发者

Reordering an array in flash as3

开发者 https://www.devze.com 2023-02-19 02:46 出处:网络
I have an array of objects, each of which is assigned an ID when it is first created. I give the user the ability to visually reorder the objects, which changes their posi开发者_开发百科tion in the ar

I have an array of objects, each of which is assigned an ID when it is first created. I give the user the ability to visually reorder the objects, which changes their posi开发者_开发百科tion in the array. They then have the option to save that order using a flash sharedObject or "cookie" and then later, if they reopen the flash file, I want them to be able to hit a button to restore that order. I'm just not sure what the syntax would be to set the object's index within the array. Here's my code:

VARIABLES:

var project_settings = SharedObject.getLocal("settings"); //saves all project settings for the next time the file is opened
var project_order:Array = []; //saves project order for the next time the file is opened
var project_display:Array = []; //saves whether each project should be displayed or hidden for the next time the file is opened

SAVE CODE:

function saveOrder(){
    for (var i=0;i<project_array.length;i++){
        project_order[i] = project_array[i].id;
        project_display[i] = project_array[i].projectThumb.thumbActive;
    }
    project_settings.data.order = project_order;
    project_settings.data.active = project_display;
    //trace (project_settings.data.active[1]);
    project_settings.flush(); //saves most recent "cookie"
}

RESTORE CODE:

function loadOrder(){
     for (var i=0;i<project_array.length;i++){
/* NEED THE CODE THAT GOES HERE. BASICALLY, PROJECT_ARRAY[i] SHOULD BE THE ITEM WITH AN ID EQUAL TO PROJECT_SETTINGS.DATA.ORDER[i] */
     }


}


Something like this should work:

function loadOrder()
{
    var dict = new Dictionary();

    for (var i = 0; i < project_array.length; i++)
        dict[project_array[i].id] = project_array[i];

    project_array = [];

    for (var i = 0; i < project_settings.data.order.length; i++)
        project_array[i] = dict[project_settings.data.order[i]];
}


Just load in your array and sort on the ID. Something like this should work:

private function _loadArray():void
{
    // fill in your array
    project_array.sort( this._sortFunc );
}

// replace the * by whatever your object type is
private function _sortFunc( a:*, b:* ):int
{
    return a.id - b.id;
}

More info: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html#sort()

Or even the sortOn() function (which might be easier) should work: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html#sortOn()

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号