Differentiating between store changes in Flux? - reactjs-flux

I have two views (A, B) that listen to a store (S), so if the store changes, it emits a change to both views.
Let's say both A and B send actions (X and Y respectively) to update S. A is suppose to update on the change that X made, but not on Y's and vice versa for B.
However, because of race conditions, I don't know what order X or Y finishes and because S simply emits a change without differentiating whether the change was caused by X or Y, I don't know whether to update A or B. So when S emits a change event, how would I be able to figure out which view to update (A or B, i.e. which action happened [X or Y]?) using Flux?

Register two different action handlers for X and Y in the store. Set a lastChangeFrom string property on the store to respectively equal 'x' or 'y'.
Then, check the nextProps.store.lastChangeFrom property in your React component's shouldComponentUpdate(nextProps, nextState) function:
// Component A
// listens for changes from action X
React.createClass({
// ...
shouldComponentUpdate: function(nextProps, nextState) {
return nextState.lastChangeFrom == 'x';
}
// ...
});
// Component B
// listens for changes from action Y
React.createClass({
// ...
shouldComponentUpdate: function(nextProps, nextState) {
return nextState.lastChangeFrom == 'y';
}
// ...
});
This way, both Component A and B will receive updates from the store but will only process them if the origin is the respective action.
Keep in mind that the store itself will still reflect all updates, regardless from their originating action. E.g. triggering different updates from Y multiple times, then triggering another update from X will apply the store state from all intermediate updates to Component A.
This answer assumes you're using Facebook's flux dispatcher / pattern. Other flux libraries such as flummox may behave differently, e.g. changes from stores would come in via nextProps instead of nextState.

You can try using EventEmitter2 for the Store which allows for namespaced events. The store can emit a change.x in response to X action, and change.Y in response to Y action. Likewise, your views A and B can now differentiate between the change events.

Related

Game Maker - Mouse Click image_index Checking

I have this sprite: spr_meteoriteLv3, which has two sub-images with index image_index 0 and 1 respectively.
I have these objects: obj_meteoriteLv3, obj_tempMeteoriteLv3, and obj_score. Object obj_meteoriteLv3 spawns from above with random position, random amount, and random sub-image. Object obj_tempMeteoriteLv3 makes obj_meteoriteLv3s spawn. When player clicks on a meteorite, the program checks the value of image_index for that object.
obj_meteoriteLv3 has these events:
Create Event: change sprite_index into spr_meteoriteLv3, and start moving downwards.
Left-pressed Mouse Event: destroy the self instance, and check image_index: if image_index == 0 then score += 5; else score -= 5).
obj_tempMeteoriteLv3 has these events:
Create Event: set Alarm 0 to 3600, set variable exist to 1, and set variable add to 1.
Alarm 0: set variable add to 0, and destroy the obj_meteoriteLv3 instance.
Alarm 1: set variable exist to 1.
Step Event: if (exist == 1) then, if (add == 1) then create instance of obj_meteoriteLv3, set variable exist to 0, and set Alarm 1 to 10.
obj_score has these events:
Create Event: set score to 0.
Draw Event: draw the value of score.
The problem is, no matter which sub-image the meteorite image_index has when clicked, the score will always be incremented by 5 points. It's like the else condition isn't working. How can I fix this? Please explain your answer. Thanks.
I add some images for better understanding. Link 1. Link 2
In obj_meteoriteLv3 it's being destroyed before it can execute the rest of the code blocks. Move "Destroy Instance" to the bottom.
In obj_tempMeteoriteLv3 both variables "add" and "exist" are not necessary, instead have-
Create Event-
alarm[0] = 3600
alarm[1] = 10
Alarm[0] Event-
destroy_instance
Alarm[1] Event
Create_instance of obj_meteoriteLv3
alarm[1] = 10
Potentially, when you click, every single meteorite is triggered.
On the left click event of the meteorite, you did not check if the cursor was on the sprite. You have to use the position_meeting function, to which you pass the mouse position and the instance to click.
it would look like :
if (position_meeting(mouse_x, mouse_y, id))
{
//your destroy code
}
Moreover, when the instance_destroy(); line is read, the following code is ignored and the program jumps to the destroy_event. William explained it well and suggested to change the order of the lines of code, but you can also change the score in the destroy event directly.
I would like to add that checking for clicks in every instance of the meteorites is not optimal for performances.
My recommendation would be to use a single object to check for clicks (your player or your meteorite spawner, for example), in which you would check for clicks, and if a meteorite is touched, you would trigger it's destroy event. And in this event, you would increment the score and check the sprite.
Your click event would look like :
with (instance_position(mouse_x, mouse_y, obj_meteoriteLv3))
{
instance_destroy();
}
and in the meteorite destroy event, you would check the image_index and change the score accordingly.
EDIT : why the score doesn't change
I believe you didn't declare the score as a global variable, but as an instance variable. So when you write "score = ..." in an other object, it creates a new score variable, unrelated to the precedent.
You have 2 options :
1 - Declare the score a global variable in the create event of obj_score:
globalvar score;
score = //your starting score
Be aware that a global variable can't be set on it's initialisation line.
2 - Change the score through the score object :
whenever the score has to change :
obj_score.score = ...

How to code against logic that depends on the current time in AngularJS?

I have some code and the result of it depends on the current time. Say,
Shop.prototype.isOpen = function() {
var now = new Date();
var today = now.getDay();
return this.openTime(today) <= now && now <= this.closeTime(today);
};
And then in the view, we display whether a shop is open:
<span ng-show="shop.isOpen()">Open now!</span>
The isOpen method is called once and doesn't get updated after that.
I have lots of complex application logic that depends on the isOpen and similar "time-bound" data.
What are the general approaches to keep the isOpen data fresh and have application logic/view be constantly in sync with that?
I think one solution would be to have an intermediate object whose value gets updated in frequent intervals, but I'm not sure if this is the right approach.
The angular documentation on directives has an example of time being updated.
http://docs.angularjs.org/guide/directive
But basically, have your controller set a $scope (or $rootScope, depending on how you want to access it) property that gets updated via a setTimeout loop.

Update a controller model in angularjs in a directive

I tried to understand angularJS, which has a different approach from what I have seen with its dirty check model update.
Basically, I have a directive ng-draggable which make elements... draggable. I have a model linking with each of this element with attribute x and y – the position of the element linked with the model – and I want the directive to update the model.
To do so, I tried to use the $apply function in my directive and set the model value x and y. Then I also use the $observe function to update the view: here is my jsfiddle. (Note I use a factory to catch the mouse event)
var mousemove = function(event) {
var y = event.screenY - startY;
var x = event.screenX - startX;
scope.$apply(function(){
attr.$set('ngModel', {'x': x, 'y': y});
});
}
It seems to work fine. However when I check the model value with the save button (it prints the model in the console), the position x and y are not updated.
So my question is how do I make it work? And more generally what is happening here? Any reading suggestion around the MVC pattern in angularJS (I found the Developer guide a bit harsh for a beginner)
Thank you for your help.
The problem on your approach is that you are changing the entire ngModel reference instead of changing just one of its properties (x and/or y). When you do that, you loose the connection to the initial ngModel (objects inside players array) and consequently the connection to the 'real' model (object play).
Try doing it like this:
scope.$apply(function() {
model.$modelValue.x = event.screenX - startX;
model.$modelValue.y = event.screenY - startY;
});
jsFiddle: http://fiddle.jshell.net/y7nVJ/

Scope for Actionscript 2.0 Event

I'm using Actionscript 2.0 for a mobile phone and can't get my head around Events.
I'm creating a class object with all my code and using a group of functions (all as direct 1st level children of the class). There's one function that creates a Movieclip with a square on it and sets the onPress event to another function called hit:
public function draw1Sqr(sName:String,pTL:Object,sSide:Number,rgb:Number){
// create a movie clip for the Sqr
var Sqr:MovieClip=this.canvas_mc.createEmptyMovieClip(sName,this.canvas_mc.getNextHighestDepth());
// draw square
Sqr.beginFill(rgb);
//etc ...more lines
//setup properties (these are accessible in the event)
Sqr.sSide=sSide;
Sqr.sName=sName;
//setup event
Sqr.onPress = hit; // this syntax seems to lead to 'this' within
// the handler function to be Sqr (movieclip)
//Sqr.onPress = Delegate.create(this, hit);
//I've read a lot about Delegate but it seems to make things harder for me.
}
Then in my event handler, I just cannot get the scope right...
public function hit(){
for (var x in this){
trace(x + " == " + this[x]);
}
//output results
//onPress == [type Function]
//sName == bSqr_7_4
//sSide == 20
trace(eval(this["._parent"])); //undefined
trace(eval(this["._x"])); //undefined
}
For some reason, although the scope is set to the calling object (Sqr, a Movieclip) and I can access properties I defined, I can't use the 'native' properties of a Movieclip object.
Any suggestions on how I can access the _x, _y and other properties of the Movieclip object that is pressed.
Use the array accessor or the dot accessor, but not both. For example:
trace(this._parent); // OR
trace(this["_parent"]);
As for the results of your iteration, I recall AS2 being screwy on this front. IIRC only dynamic properties are returned when looping with for ... in. This prevents Objects (which often serve as hash maps) from including their native properties when all you want are the key/value pairs you set yourself.
Also - the eval() function can be easily overused. Unless you absolutely must execute a String of AS2 that you don't have at compile-time I would recommend avoiding it. Happy coding!

Is there a way to break out of event recursion in jQuery without using a global variable?

I have a form with 2 text inputs and 2 span controls. Normally, when textbox A is changed an event is fired to change span A, and when textbox B is changed, an event is fired to change span B.
However, in one particualar case I would like a change either textbox A or textbox B to update both span A and B. I tried wiring the events up to the corresponding controls in this case, but it didn't work because there is much state that is set up in the event building code (not to mention each event calls 'this', which would make the logic use the wrong control if it were fired from a different one than it was intended).
To make things easy, it would be best to pass a string (representing the other text input id) to the event handler at the time it is created, and then calling the change() event manually on the second control. However, this puts things in an infinite loop of recursion. I thought of a way to get around the recursion, but it reqires a global variable.
Is there a better way than this, preferably one that doesn't require a global variable?
ml_inEvent = false;
$ctlToVal.bind('keyup change', {feedbackCtl: ml_feedback, controlsToMonitor: ary, validationGroup: this.validationGroup, controlToFire: ctlToFire}, function(event) {
// Other processing happens here...
if (event.data.controlToFire != '') {
var $controlToFire = $('#' + event.data.controlToFire);
if ($controlToFire.length) {
// Use a global variable to ensure this event is not fired again
// as a result of calling the other one
if (!ml_inEvent) {
ml_inEvent = true;
$controlToFire.change();
ml_inEvent = false;
}
}
}
});
You can use the extraParameters argument on .trigger() to break out, for example:
$ctlToVal.bind('keyup change', {feedbackCtl: ml_feedback, controlsToMonitor: ary, validationGroup: this.validationGroup, controlToFire: ctlToFire}, function(event, fire) {
// Other processing happens here...
if(fire !== false) $('#' + event.data.controlToFire).trigger('change', false);
});
You can give it a try here. What this does is the event handler callback not only receives the event object but also any other arguments you pass in, in this case we're just using a simple false and a !=== check this in important so undefined (the parameter not passed at all) still changes both controls. So for instance $("#control").change() would change both controls, but still not loop...you can test that here.

Resources