ActionScript object name by variable - apache-flex

In this example:
var poets:Array = new Array();
poets.push({name:"Angelou", born:"1928"});
poets.push({name:"Blake", born:"1757"});
poets.push({name:"cummings", born:"1894"});
poets.push({name:"Dante", born:"1265"});
poets.push({name:"Wang", born:"701"});
Is it possible for 'name' and 'born' to be variables?

As #RIAstar points out, they are properties of an 'associative array' - your dynamic Object{}:
var poets:Array = new Array();
poets.push({"name":"test","born":"1928"});
poets.push({name:"Angelou", born:"1928"});
poets.push({name:"Blake", born:"1757"});
poets.push({name:"cummings", born:"1894"});
poets.push({name:"Dante", born:"1265"});
poets.push({name:"Wang", born:"701"});
trace(poets[0].name,poets[0].born);
or if a more expanded version:
var prop1:String = "name";
var prop2:String = "born";
var poets:Array = [];
poets[0] = {};
poets[0][prop1] = "test2";
poets[0][prop2] = "1900";
trace(poets[0].name,poets[0].born);

If you want to create a function that returns data given the attribute name, you can do something like this:
public function getDataByAttribute(fieldName:String):Array {
return poets.map(
function (item:*, index:int, array:Array):String {
return item[fieldName];
}
);
}
// sample call
var results:Array = getDataByAttribute("born");
You can modify it to suit your needs.
To explore Array's functions, see this blog (not mine).

Related

How to bind/referece grand parent property to/inside child knockout

Hi guys looking for some basic advice.
I have four models: BoardViewModel, List, Card, Member
var Member = function (id, name, avatar) {
var self = this;
self.id = id;
self.name = name;
self.avatar = avatar;
self.isChecked = ko.observable(false);
};
I am instantiating members property inside BoardViewModel. But I want to use a copy of this model inside each Card model to instantiate a list of assigned members.
Each card stores comma separated list of member references like
",1,2,4,5"
I am writing a loop to BoardViewModel.members and mark members as checked if id references match bore I assign it as Card.members.
The last piece of the puzzle I am missing is reference to the BoardViwModel.members.
I have a lovely example fiddler that would somewhat help to build a picture of what I am talking about.
Just bear in mind that once I have this working properly I want to replace view() binding
foreach: $root.members
with
foreach: members
If at all possible I would like to avoid passing BoardViewModel.members as parameter into List and then into Card.
Update 1
As suggested by #Jeroen here's a simplified version of my fiddler.
The top view() model which encompases a concept of lists:
var BoardViewModel = function (lists, members) {
var self = this;
// in reality members are fetched via ajax call to the server
// and instantiate as a ko.observableArray()
self.groupMembers = ko.observableArray(members);
self.lists = ko.observableArray(lists);
...
}
In reality this has a signature like this:
var boardViewModel = function (initialData)
moving on.
The child List model which encompases a concept of cards:
var List = function (id, name, cards, sortOrder, groupMembers) {
var self = this;
self.cards = ko.observableArray(cards);
...
}
in reality:
var list = function (item, groupMembers)
nothing special there really.
The child Card model which encompases the concept of card items (but lets not go there yet):
var Card = function (id, title, description, contentItemId, members, groupMembers) {
var self = this;
self.members = ko.observableArray(parseMembers(members));
// now remember each card has a members property
// which stores comma separated list ",1,4"
function (members) {
var memberList = groupMembers;
var memberRefList = members.split(',');
ko.utils.arrayForEach(memberList, function(member){
ko.utils.arrayForEach(memberRefList, function(memberId){
if(member.id === meberId) {
member.isChecked(true);
}
});
});
return memberList;
}
...
}
in reality:
var card = function (item, groupMembers)
nothing too fancy there either.
I currently have something like this working on my dev environment.
Problem:
Those with keen eyes probably noticed the way I was passing groupMembers all the way up. I am not particularly hyped about the idea.
Anyone know a better way of implementing this? i.e. why can't I just do something like
var memberList = self.parent.parent.groupMembers;
for instance.
As per me, the better way to do is to have the child viewmodels inside the parent view-model. like this where you can access the parent data members as well as methods directly.
ViewModel
var BoardViewModel = function(){
var self = this;
this.members = ko.observableArray();
this.lists = ko.observableArray();
// Child View Models
this.Member = function(member){
this.id = member.id;
this.name = member.name;
this.avatar = member.avatar;
this.isChecked = ko.observable(false);
}
this.List = function(list){
// same for this
};
this.Card = function(card){
// same for this
};
// a Method to bind the data with the observables and arrays
// Assuming data is a json object having Members, List objects
this.applyData = function(data){
self.members(jQuery.map(data.Members, function(item){
return new self.Member(item);
}));
self.lists(jQuery.map(data.Lists, function(item){
return new self.List(item);
}));
}
}
onDom ready
// json object holding your data
var data = {
"Members" : [
],
"Lists" : [
],
"Cards" : [
]
};
var vm = new BoardViewModel();
$(function(){
ko.applyBindings(vm, document.getElementById('myModule'));
vm.applyData(data);
});

google places api many filters by type Ex.: restaurant,cafe

I'm trying to change the radius category/type filter for a checkbox, so I changed the var type to an array.
ORIGINAL WORKING:
var type;
for (var i = 0; i < document.controls.type.length; i++){
if (document.controls.type[i].checked){
type = document.controls.type[i].value;
}
}
startBox.setBounds(map.getBounds());
var search = {
// keyword: 'comocomo', // not needed with the autocomplete / startBox
bounds: map.getBounds()
};
if (type != 'establishment'){
search.types = [ type ];
}
places.search(search, function(placesArr, status){
THE ONE WITH THE ARRAY NOT WORKING: edited:
var type=[];
for (var i = 0; i < document.controls.type.length; i++){
if (document.controls.type[i].checked){
type.push(document.controls.type[i].value)
}
}
startBox.setBounds(map.getBounds());
var search = {
bounds: map.getBounds()
};
var quotedAndCommaSeparated = "'" + type.join("','") + "'";
alert(quotedAndCommaSeparated); // 'establishment','restaurant','lodging'
search.types = [ quotedAndCommaSeparated ];
I made many tests, and I don't see what I'm doing wrong. the map doesn't even show.
What's this meant to be, doesn't look like valid Javascript to me:
var type[];
Should be
var type = [];
Fix the javascript errors in your code otherwise the map won't show up.
Update:
What you have in quotedAndCommaSeparated is a string like "'a','b','c'" that looks a bit like the contents of an array: ['a','b','c']. But it's not an array, it's just a single string. If you check the length of your search.type array, I'm guessing it equals 1.
What you can do is split your string on the comma to turn it into an array:
search.types = quotedAndCommaSeparated.split(",");

AdvancedDatagrid GroupingCollection in AS3

My AIR-Application is based on Mate.
I receive Data from a SQLite and put the Date into a ArrayCollection.
In the class of my AdvancedDataGrid, i create a GroupingCollection via mxml. All works fine.
I prefer to build the GroupingCollection in Actionscript. But i can't find anything, how to code this.
In the adobe help itself, they create a GroupingCollection in mxml.
The goal is, to instanciate the gc in model of mate for another class. This will be a chart and the dataProvider must be the gc.
Another Idea is, to build the groupingCollection and put it into the model via two-way-bindung. But I'm not sure, if this will work.
Have you any hint for me?
Thank you
Frank
It works like this. What a fight.
private function onCreationComplete () :void
{
adg.dataProvider = createDataProvider();
}
private function createDataProvider () :GroupingCollection2
{
var tmp:GroupingCollection2 = new GroupingCollection2();
tmp.source = dpArrColl;
tmp.grouping = adgGrouping();
tmp.refresh(false);
return tmp;
}
private function adgGrouping () : Grouping
{
var tmp:Grouping = new Grouping();
tmp.fields = [groupingFieldArray()];
return tmp;
}
private function groupingFieldArray () :GroupingField
{
var tmp:GroupingField = new GroupingField();
tmp.name = "groupName1";
tmp.summaries = [adgSummaries()];
return tmp;
}
private function adgSummaries () : SummaryRow
{
var tmp:SummaryRow = new SummaryRow();
tmp.summaryPlacement = "group";
tmp.fields = [adgSummaryFiled1(), adgSummaryField2()];
return tmp;
}
private function adgSummaryFiled1 () :SummaryField2
{
var tmp:SummaryField2 = new SummaryField2();
tmp.dataField = "Sumfiel1";
tmp.summaryOperation = "SUM";
return tmp;
}
private function adgSummaryField2 () : SummaryField2
{
var tmp:SummaryField2 = new SummaryField2();
tmp.dataField = "Sumfield2";
tmp.summaryOperation = "COUNT";
return tmp;
}
I hope, someone will help this someday.
BR
Frank

Flash/Flex: Is it possible to encode Dictionary using AMF?

As the title suggests, is it possible to use AMF to encode/decode Dictionaries (without subclassing, that is)?
For example, here's a test case:
function serializeAndReload(obj:*):* {
var serialized:ByteArray = new ByteArray();
serialized.writeObject(obj);
serialized.position = 0;
return serialized.readObject();
}
function test():void {
var d:Dictionary = new Dictionary();
d[{}] = 42;
d[d] = true;
var x:* = serializeAndReload(d); // <<< x is an instance of Object
trace(x['[object Object]']); // <<< traces '42'
}
You may be over-thinking. I use Object instead of Dictionary and it is automatically encoded using AMF. I use pyamf all the time to pass Objects/dicts around and its always worked without any mental effort on my part. Never have I needed to manually serialize/deserialize anything
The keys in the Dictionary need to be serializable, too.
[RemoteClass(alias="Foo")]
public class Foo
{
}
Test:
var d:Dictionary = new Dictionary();
var f:Foo = new Foo();
d[f] = "Hello";
var ba:ByteArray = new ByteArray();
ba.writeObject(d);
ba.position = 0;
var d2:Dictionary = Dictionary(ba.readObject());
for (var key:* in d2)
{
trace(getQualifiedClassName(key));
trace(d2[key]);
}
Output:
Foo
Hello

Flex: Sort -- Writing a custom compareFunction?

OK, I am sorting an XMLListCollection in alphabetical order. I have one issue though. If the value is "ALL" I want it to be first in the list. In most cases this happens already but values that are numbers are being sorted before "ALL". I want "ALL" to always be the first selection in my dataProvider and then the rest alphabetical.
So I am trying to write my own sort function. Is there a way I can check if one of the values is all, and if not tell it to do the regular compare on the values?
Here is what I have:
function myCompare(a:Object, b:Object, fields:Array = null):int
{
if(String(a).toLowerCase() == 'all')
{
return -1;
}
else
if(String(b).toLowerCase() == 'all')
{
return 1;
}
// NEED to return default comparison results here?
}
//------------------------------
var sort:Sort = new Sort();
sort.compareFunction = myCompare;
Is there a solution for what I am trying to do?
The solution from John Isaacks is awesome, but he forgot about "fields" variable and his example doesn't work for more complicated objects (other than Strings)
Example:
// collection with custom objects. We want to sort them on "value" property
// var item:CustomObject = new CustomObject();
// item.name = 'Test';
// item.value = 'Simple Value';
var collection:ArrayCollection = new ArrayCollection();
var s:Sort = new Sort();
s.fields = [new SortField("value")];
s.compareFunction = myCompare;
collection.sort = s;
collection.refresh();
private function myCompare(a:Object, b:Object, fields:Array = null):int
{
if(String((a as CustomObject).value).toLowerCase() == 'all')
{
return -1;
}
else if(String((b as CustomObject).value).toLowerCase() == 'all')
{
return 1;
}
// NEED to return default comparison results here?
var s:Sort = new Sort();
s.fields = fields;
var f:Function = s.compareFunction;
return f.call(null,a,b,fields);
}
Well I tried something out, and I am really surprised it actually worked, but here is what I did.
The Sort class has a private function called internalCompare. Since it is private you cannot call it. BUT there is a getter function called compareFunction, and if no compare function is defined it returns a reference to the internalCompare function. So what I did was get this reference and then call it.
private function myCompare(a:Object, b:Object, fields:Array = null):int
{
if(String(a).toLowerCase() == 'all')
{
return -1;
}
else if(String(b).toLowerCase() == 'all')
{
return 1;
}
// NEED to return default comparison results here?
var s:Sort = new Sort();
var f:Function = s.compareFunction;
return f.call(null,a,b,fields);
}
Thanks guys, this helped a lot. In our case, we needed all empty rows (in a DataGrid) on the bottom. All non-empty rows should be sorted normally. Our row data is all dynamic Objects (converted from JSON) -- the call to ValidationHelper.hasData() simply checks if the row is empty. For some reason the fields sometimes contain the dataField String value instead of SortFields, hence the check before setting the 'fields' property:
private function compareEmptyAlwaysLast(a:Object, b:Object, fields:Array = null):int {
var result:int;
if (!ValidationHelper.hasData(a)) {
result = 1;
} else if (!ValidationHelper.hasData(b)) {
result = -1;
} else {
if (fields && fields.length > 0 && fields[0] is SortField) {
STATIC_SORT.fields = fields;
}
var f:Function = STATIC_SORT.compareFunction;
result = f.call(null,a,b,fields);
}
return result;
}
I didn't find these approaches to work for my situation, which was to alphabetize a list of Strings and then append a 'Create new...' item at the end of the list.
The way I handled things is a little inelegant, but reliable.
I sorted my ArrayCollection of Strings, called orgNameList, with an alpha sort, like so:
var alphaSort:Sort = new Sort();
alphaSort.fields = [new SortField(null, true)];
orgNameList.sort = alphaSort;
orgNameList.refresh();
Then I copied the elements of the sorted list into a new ArrayCollection, called customerDataList. The result being that the new ArrayCollection of elements are in alphabetical order, but are not under the influence of a Sort object. So, adding a new element will add it to the end of the ArrayCollection. Likewise, adding an item to a particular index in the ArrayCollection will also work as expected.
for each(var org:String in orgNameList)
{
customerDataList.addItem(org);
}
Then I just tacked on the 'Create new...' item, like this:
if(userIsAllowedToCreateNewCustomer)
{
customerDataList.addItem(CREATE_NEW);
customerDataList.refresh();
}

Resources