Capturing mouseEevents on a container, bypassing its children - apache-flex

I am building an RIA application using Flex 4.6 that contains a main borderContainer (page) that can contain some other borderContainers (graphic or text elements).
I added an event listener on the page to listen to click events:
page.addEventListener(MouseEvent.CLICK, clickHandler, true);
clickHandler looks like this:
private function clickHandler(event:MouseEvent):void
{
// Remove event listeners
page.removeEventListener(MouseEvent.CLICK, clickHandler, true);
// Get click position
objX = event.localX;
objY = event.localY;
}
My problem is that although the event's currentTarget is always the page (normal), the target can either be the page or one of its children, and then localX doesn't give me the position on the page but on the child.
Is there a way to make sure the page is always the target of the event? Something like stopping the capturing phase on the page so it doesn't go deeper?
Thanks in advance for your help
Darrel

I think you may be asking the wrong question. As I understand it, you want the x/y position relative to 'page'. You can use the DisplayObject#globalToLocal() function to find this.
Just take the the global coordinates and convert them to local coordinates relative to 'page':
var coordinates:Point = new Point(event.stageX, event.stageY);
coordinates = page.globalToLocal(coordinates);
objX = coordinates.x;
objY = coordinates.y;

Related

How to keep a list from scrolling on dataProvider refresh/update/change?

I have a simple list and a background refresh protocol.
When the list is scrolled down, the refresh scrolls it back to the top. I want to stop this.
I have tried catching the COLLECTION_CHANGE event and
validateNow(); // try to get the component to reset to the new data
list.ensureIndexIsVisible(previousIndex); // actually, I search for the previous data id in the IList, but that's not important
This fails because the list resets itself after the change (in DataGroup.commitProperties).
I hate to use a Timer, ENTER_FRAME, or callLater(), but I cannot seem to figure out a way.
The only other alternatives I can see is sub-classing the List so it can catch the dataProviderChanged event the DataGroup in the skin is throwing.
Any ideas?
Actually MUCH better solution to this is to extend DataGroup. You need to override this.
All the solutions here create a flicker as the scrollbar gets resetted to 0 and the it's set back to the previous value. That looks wrong. This solution works without any flicker and the best of all, you just change DataGroup to FixedDataGroup in your code and it works, no other changes in code are needed ;).
Enjoy guys.
public class FixedDataGroup extends spark.components.DataGroup
{
private var _dataProviderChanged:Boolean;
private var _lastScrollPosition:Number = 0;
public function FixedDataGroup()
{
super();
}
override public function set dataProvider(value:IList):void
{
if ( this.dataProvider != null && value != this.dataProvider )
{
dataProvider.removeEventListener(CollectionEvent.COLLECTION_CHANGE, onDataProviderChanged);
}
super.dataProvider = value;
if ( value != null )
{
value.addEventListener(CollectionEvent.COLLECTION_CHANGE, onDataProviderChanged);
}
}
override protected function commitProperties():void
{
var lastScrollPosition:Number = _lastScrollPosition;
super.commitProperties();
if ( _dataProviderChanged )
{
verticalScrollPosition = lastScrollPosition;
}
}
private function onDataProviderChanged(e:CollectionEvent):void
{
_dataProviderChanged = true;
invalidateProperties();
}
override public function set verticalScrollPosition(value:Number):void
{
super.verticalScrollPosition = value;
_lastScrollPosition = value;
}
}
I ll try to explain my approach...If you are still unsure let me know and I ll give you the source code as well.
1) Create a variable to store the current scroll position of the viewport.
2) Add Event listener for Event.CHANGE and MouseEvent.MOUSE_WHEEL on the scroller and update the variable created in step 1 with the current scroll position;
3) Add a event listener on your viewport for FlexEvent.UpdateComplete and set the scroll position to the variable stored.
In a nutshell, what we are doing is to have the scroll position stored in variable every time user interacts with it and when our viewport is updated (due to dataprovider change) we just set the scroll position we have stored previously in the variable.
I have faced this problem before and solved it by using a data proxy pattern with a matcher. Write a matcher for your collection that supports your list by updating only changed objects and by updating only attributes for existing objects. The goal is to avoid creation of new objects when your data source refreshes.
When you have new data for the list (after a refresh), loop through your list of new data objects, copying attributes from these objects into the objects in the collection supporting your list. Typically you will match the objects based on id. Any objects in the new list that did not exist in the old one get added. Your scroll position will normally not change and any selections are usually kept.
Here is an example.
for each(newObject:Object in newArrayValues){
var found:Boolean = false;
for each(oldObject:Object in oldArrayValues){
if(oldObject.id == newObject.id){
found = true;
oldObject.myAttribute = newObject.myAttribute;
oldObject.myAttribute2 = newObject.myAttribute2;
}
}
if(!found){
oldArrayValues.addItem(newObject);
}
}
My solution for this problem was targeting a specific situation, but it has the advantage of being very simple so perhaps you can draw something that fits your needs from it. Since I don't know exactly what issue you're trying to solve I'll give you a description of mine:
I had a List that was progressively loading data from the server. When the user scrolled down and the next batch of items would be added to the dataprovider, the scrollposition would jump back to the start.
The solution for this was as simple as stopping the propagation of the COLLECTION_CHANGE event so that the List wouldn't catch it.
myDataProvider.addEventListener(
CollectionEvent.COLLECTION_CHANGE, preventRefresh
);
private function preventRefresh(event:CollectionEvent):void {
event.stopImmediatePropagation();
}
You have to know that this effectively prevents a redraw of the List component, hence any added items would not be shown. This was not an issue for me since the items would be added at the end of the List (outside the viewport) and when the user would scroll, the List would automatically be redrawn and the new items would be displayed. Perhaps in your situation you can force the redraw if need be.
When all items had been loaded I could then remove the event listener and return to the normal behavior of the List component.

Help with containers

I am using view stack...so when view change like when we move from one page to another hide event is dispatched.So i am saving the information of last page in hide event before i go to next page.but thing is that if i change nothing still change on view hide event is invoked nd call go to backend...i just want do call only if sumthing change in the view..like sum text value...So i have two options
use event listener on each component if sumthing change its make the flag true...nd hide event check, if flag is true send call to backend.
event listener at container level ..if sumthing change in child componenet through bubbling container knows if sum event is dispatched.nd makes the flag true.
I have doubt with container...
Can i use container, and how?
Reason why I can't use container?
What are the pros and cons either way?
I would recommend using a dataProvider with the ability to compare them. For instance, if you are changing things with textinputs, you could basically do something like this:
[Bindable]
private var myDataProvider:Object = new Object();
private function creationCompleteHandler():void {
myDataProvider.updated = false;
myDataProvider.defaultValue = 'default';
myDataProvider.defaultValueTwo = 'default';
}
etc.
Then, in your mxml, you can have something like this:
<mx:TextInput id="myText" text="{myDataProvider.defaultValue}" change="myDataProvider.defaultValue=myText.text; myDataProvider.updated=true;" />
Lastly, in your hide event, you can do the following:
private function hideEventHandler( event:Event ):void {
if( myDataProvider.updated ){
// Call your RemoteServices (or w/e) to update the information
}
}
This way, when anything changes, you can update your dataProvider and have access to the new information each time.
Hope this helps!
I've used an approach similar to your first option in a couple of my past projects. In the change event for each of my form's controls I make a call to a small function that just sets a changesMade flag to true in my model. When the user tries to navigate away from my form, I check the changesMade flag to see if I need to save the info.
Data models are your friend!
If you get in the habit of creating strongly typed data models out of your loaded data, questions like this become very basic.
I always have a key binding set to generate a code snipit similar to this...
private var _foo:String;
public function get foo():String
{
return _foo;
}
public function set foo(value:String):void
{
if(_foo == value)
return;
var oldVal:String = _foo;
_foo = value;
this.invalidateProperty("foo", oldVal, value);
}
If your data used getters/setters like this, it would be very easy to validate a change on the model level, cutting the view out of the process entirely.

flex- Drag and drop

I am trying to drag and drop an object across the SkinnableContainer- am coming across a very strange issue
The drop occurs only at a few places- elsewhere it just shows the "X" sign and on dropping there, reverts to original position. I have used very standard commands... from function 2 to function 3, the call occurs very rarely as seen in trace statements- any guidance on why this happens?
I added the following code to SkinnableContainer: dragEnter="dragEnterHandler(event);" dragDrop="dragDropHandler(event);
(1):
private function mouseMoveHandler(event:MouseEvent):void
{
var dragInitiator:Image = Image(event.currentTarget);
var ds:DragSource = new DragSource();
ds.addData(dragInitiator,"img"); //made change here
DragManager.doDrag(dragInitiator, ds, event);
}
(2):
private function dragEnterHandler(event:DragEvent):void {
if (event.dragSource.hasFormat("img"))
{
trace("came here"); //comes here for each mouse move
DragManager.acceptDragDrop(SkinnableContainer(event.currentTarget));
}
(3):
private function dragDropHandler(event:DragEvent):void {
trace("in drag drop handler"); //doesn't come here for most places
According to the Using Flex 4 reference:
To use a container as a drop target, you must use the backgroundColor property of the container to set a color. Otherwise, the background color of the container is transparent, and the Drag and Drop Manager is unable to detect that the mouse pointer is on a possible drop target.
In the subsequent example, they use an mx container (Canvas), but I checked the AS3 reference, and spark.components.SkinnableContainer does have a style backgroundColor.
I haven't tried this myself, so please confirm whether it is the issue. From your description that only certain parts of the container are registering the dragEnter event, this seems like a consideration that would lead to such effects.

Flex 3: Embedding MovieClip Symbol to Image Control programmatically

I've reviewed all the documentation and Google results surrounding this and I think I have everything setup correctly. My problem is that the symbol is not appearing in my app. I have a MovieClip symbol that I've embedded to my Flex Component. I need to create a new Image control for each item from my dataProvider and assign this embedded symbol as the Image's source. I thought it was simple but apparently not. Here's a stub of the code:
[Embed(source="../assets/assetLib.swf", symbol="StarMC")]
private var StarClass:Class;
protected function rebuildChildren():void {
iterator.seek( CursorBookmark.FIRST );
while ( !iterator.afterLast ) {
child = new Image();
var asset:MovieClipAsset = new StarClass() as MovieClipAsset;
(child as Image).source = asset;
}
}
I know the child is being created because I can draw a shape and and that appears. Am I doing something wrong? Thank you!
You should be able to simply set child.source to StarClass:
child = new Image();
child.source = StarClass;
See the MovieClipAsset Language Reference for more details:
you rarely need to create MovieClipAsset instances yourself
because image-related properties and
styles can be set to an
image-producing class, and components
will create instances as necessary.
For example, to set the application
background to this animation, you can
simply write the following:
<mx:Application backgroundImage="{backgroundAnimationClass}"/>

Problems with itemRollOver and itemRollOut events on List component

I have set the itemRollOver and itemRollOut event listeners on a List component, but whenever I roll the mouse over a list item, both the over and out events of the same list item fire in succession right after each other. My list uses a custom itemRenderer.
Any ideas why this might be? The Adobe documentation doesn't provide much insight into this (not surprisingly...).
In my opinion this is a bug. The ListBase.mouseOverHandler now sets a variable called lastHighlightItemRendererAtIndices when it dispatches an ITEM_ROLL_OVER event, which is then used (together with lastHighlightItemIndices) when dispatching an ITEM_ROLL_OUT event in ListBase.clearHighlight (called by the mouseOutHandler).
The problem is that when you mouse from row-to-row the mouseOverHandler is called first, setting the lastHightlight... variables, and then when the mouseOutHandler gets called subsequently, it uses the lastHighlight... values that were just set with the result that you get consecutive 'roll over' and 'roll out' events for the same renderer.
Frankly I don't know why ListBase.clearHighlight just doesn't use the passed in renderer when dispatching the ITEM_ROLL_OUT event (which is how it used to work in SDK 2) as this is the actual renderer that is being 'rolled out of'.
Are they coming from the same object?
If not you will it is likely so that you will get an itemRollOut from the "item" you just left and a itemRollOver from the new one you entered, depending on their spacing and such these may fire very close to each other.
Make sure you are setting super.data in your item renderer if you are overriding set data().
ListBase listens for MOUSE_OVER and then figures out the item underneath it based on coordinates of mouse and the position of the item renderer. You could check ListEvent.itemRenderer to see which renderer's roll over and roll out are firing and in what order.
Worst case, you could listen for rollOver and rollOut inside your item renderer.
Had the same problem. super.data was already being set, and the item is the same for the rollOut and rollOver event. I ended up opting for anirudhsasikumar's worst case scenario, and listened for rollOver and rollOut inside the item renderer. Seems to work fine.
I was having this same issue. I ended up subclassing the mx.controls.List class and overriding the clearHighlight function. As far as I can tell, the lastHighlightItemIndices variable is only ever read in that function. So doing something like the following fixed this issue:
import mx.core.mx_internal;
use namespace mx_internal;
public class List extends mx.controls.List
{
public function List()
{
super();
}
override mx_internal function clearHighlight( item:IListItemRenderer ):void
{
var uid:String = itemToUID( item.data );
drawItem( UIDToItemRenderer( uid ), isItemSelected( item.data ), false, uid == caretUID );
var pt:Point = itemRendererToIndices( item );
if( pt )
{
var listEvent:ListEvent = new ListEvent( ListEvent.ITEM_ROLL_OUT );
listEvent.columnIndex = item.x;
listEvent.rowIndex = item.y;
listEvent.itemRenderer = item;
dispatchEvent( listEvent );
}
}
}
Then just use this List class instead of the Adobe one and you'll have the behavior you expect. I tested this against Flex SDK 3.2 and it works.
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:controls="com.example.controls.*">
[ other code ... ]
<controls:List itemRollOver="onItemRollOver( event )" itemRollOut="onItemRollOut( event )" />
</mx:Canvas>
Thanks to Gino Basso for the idea in the post above. Hope that helps.
Thanks for the solution. That really solved the problem! Small correction, though:
listEvent.columnIndex = item.x;
listEvent.rowIndex = item.y;
should be
listEvent.columnIndex = pt.x;
listEvent.rowIndex = pt.y;
item.x and y hold the coordinate of the renderer in pixels.

Resources