Dart Observable Change Handler - dart

I'm looking for a way to use a handler function to respond to changes to an observable collection in Dart. I want to pipe my change directly to a function.
List things = toObservable([]);
//...
things.onChange.listen((e) => onThingsChanged(e) ); //blows up
//...
function onThingsChanged(e){
//...
}
There obviously isn't such thing as onChange, so what am I looking for here? All the examples I find are just watching the changes with a <template> tag in the HTML.

There is a good (official) article about Observables and Data Binding with Web UI. I think it is still under construction and thus there are no links on the dartlang.org website yet.
The part that answers your question is: Expression Observers
You can do something like this:
List things = toObservable([]);
observe(() => things, onThingsChanged);
onThingsChanged(ChangeNotification e) {
// ...
}

Few additions to Marco's answer which might not be obvious.
Besides observe which takes an expression, you can also use observeChanges which takes an instance of Observable, so you can write observeChanges(things, (c) => ...).
More important is the fact that if you use ObservableList outside of Web UI context (e.g. in a standalone script), the changes will not be triggered immediately. Instead, changes are queued and you need to call deliverChangesSync to trigger the notifications. The listener will then get notified with list of changes.

Related

Add a property to an object (or at least similar outcome)

First, the context of what I'm doing. I am running an HttpServer which is handling HttpRequests.
HttpServer.bind(ADDRESS, PORT).then((HttpServer server) {
listenSubscription = server.listen(onRequest);
});
void onRequest(HttpRequest request) {
//handle request here
}
I'd like to add some logging to all this, and due to the asynchronous nature of it all, want to add some identifying marker to the requests (so I can match up the request receipts with the responses, fer example). The code inside of onRequest() calls a bunch of other functions to do different things (handle GET vs POST requests, etc.), so simply generating an id at the top is a cumbersome solution as I'd have to pass it around through all those other function calls. I am, however, already passing around the HttpRequest object, so I thought it would be nice to throw an id field on it, just like you would in Javascript, except that Dart doesn't work that way.
Thoughts then went to subclassing the HttpRequest class, but converting the HttpRequest object the onRequest() method receives seemed like much more trouble and overhead than my needs required.
So I ask, is there any idiomatic Dart way attach some data to an existing object? If there isn't something idiomatic, what is the simplest (both in code and runtime complexity) way you can think of to accomplish this?
Well, there's an Expando, but I don't know the performance implications.
Something like:
// somewhere top level. Create this once.
final loggingId = new Expando();
...
// inside of onRequest
loggingId[request] = generateId();
...
// later inside log()
print(loggingId[request]);
Expandos are like weak-reference maps, from my understanding.

Rendering Polymer element once per multiple attribute changes

I have an Polymer.dart element with multiple attributes, e.g.
<code-mirror lines="{{lines}}" widgets="{{widgets}}">
</code-mirror>
on some occasions lines and widgets change simultaneously sometimes only widgets changes.
I would like to rerender component once independently on how many properties change in the same turn of event loop.
Is there a way a good built-in way to achieve that?
Additional trouble here is that interpretation of widgets depends on content of lines and ordering in which linesChanged and widgetsChanged callbacks arrive is browser dependent, e.g. on Firefox widgetsChanged arrives first before linesChanged and component enters inconsistent state if I do any state management in the linesChanged callback.
Right now I use an auxiliary class like this:
class Task {
final _callback;
var _task;
Task(this._callback);
schedule() {
if (_task == null) {
_task = new async.Timer(const Duration(milliseconds: 50), () {
_task = null;
_callback();
});
}
}
}
final renderTask = new Task(this._render);
linesChanged() => renderTask.schedule();
widgetsChanged() => renderTask.schedule();
but this looks pretty broken. Maybe my Polymer element is architectured incorrectly (i.e. I have two attributes with widgets depending on lines)?
*Changed methods are definitely the right way to approach the problem. However, you're trying to force synchronicity in an async delivery system. Generally we encourage folks to observe property changes and react to them and not rely on methods being called in a specific order.
One thing you could use is an observe block. In that way, you could define a single callback for the two properties and react accordingly:
http://www.polymer-project.org/docs/polymer/polymer.html#observeblock
Polymer's data binding system does the least amount of work possible to rerender DOM. With the addition of Object.observe(), it's even faster. I'd have to see more about your element to understand what needs rendering but you might be creating a premature optimization.
I think there are three possible solutions:
See this: http://jsbin.com/nilim/3/edit
Use an observe block with one callback for multiple attributes (the callback will only be called once)
Create an additional attribute (i.e. isRender) that is set by the other two attributes (lines and widgets). Add a ChangeWatcher (i.e. isRenderChanged() in which you call your expensive render method)
Specify a flag (i.e. autoUpdate) that can be set to true or false. When autoUpdate = false you have to call the render method manually. If it is set to true then render() will be called automatically.
The disadvantage of solution 1 is that you can only have one behavior for all observed attributes. Sometimes you want to do different things when you set a specific attribute (i.e. size) before you call render. That's not possible with solution 1.
I don't think there is a better way. You may omit the 50ms delay (just Timer.run(() {...});) as the job gets scheduled behind the ongoing property changes anyway (my experience, not 100% sure though)

LoadOperation.Completed vs. callback in DomainContext.Load()

Using Silverlight 3 with RIA: What's the difference between the LoadOperation.Completed event and using a callback through the DomainContext.Load method? Both fire asynchronously and both provide access to the LoadOperation. When/why would I use one over the other?
Thanks :-)
There's no difference; the 2 options are offered for flexibility. Many times, the callback will suffice, but if you return the LoadOperation from a method, the caller could then choose to subscribe.
Note that even if the Load completes before you subscribe to the Completed event, your handler will still get called. We guarantee every subscriber to the event will be called.
Agreed that there is not difference in functionality. It's about coding style. If the work I have to do following completion of the query is simple, like binding data to a grid, I like the use the following syntax to inline the completed code, rather than defining a separate method.
context.Load<EntityType>(query).Completed += (lo, args) =>
{
myGrid.ItemsSource = ((LoadOperation) lo).Entities;
}
This has the cleanliness of synchronous code, but the code inside the braces will in fact be executed asynchronously.
Good luck!

How do you unwire an action in Nitrogen?

In Nitrogen, the Erlang web framework, you wire actions like this:
wf:wire(send_message, #event { type=click, postback=send_message })
but if after that you run
wf:wire(send_message, #event { type=click, postback=send_message2 }),
then you get the action wired twice.
How do you unwire the previous action or all actions of an element?
Since events in nitrogen are bound using jquery's bind method. You can use unbind to unbind them. There isn't currently a nitrogen api to unbind an event but you could output the javascript code to unbind it yourself if you so wished.
see action_event.erl for an example of how the binding javascript is output. You can create a similar action/event that removes the binding.
I too was looking for an "unwire" and didn't find it. My work-around was to wf:replace() the element to which the event was wired, and wire the replacement element; I hope that javascript will eventually notice the former bind can never be called and then garbage collect it. I don't know how expensive such abandoned bindings are. My context was a lazy loading of the page, such that a button would initially show a stub, but when clicked would download arbitrarily large content, and henceforth toggle hide/show.
Beyond being nervous about the sophistication of the javascript garbage collection, I'm worried that this may be a bad pattern, and would love to hear others' experience. The only alternative that occurs to me would be to keep state (e.g. data) in the original element and pass that state back with the event message so that the same event handler would act on the "unloaded->loaded_show->loaded_hide->loaded_show" transitions. But I'd prefer not to be calling back to the server for a simple hide/show transition.

Can a 'while loop' be used in actionscript to monitor an event dispatch?

I am creating an action script library.I am calling some APIs which parses some xml and gets me the result. It dispatches an Event.COMPLETE when the parsing is done. I want to monitor whether this event is dispatched in some while loop like "while(eventnotdispatched)"
is it possible? I know the other way would be to addeventlistener. But please let me know if the other thing is possible.
Thanks
NO, it is not possible. Actionscript is single threaded. Thus while you are waiting in your while loop, that is the only thread running, and the process you are waiting for can never complete. This is why everything is done with events, so that's what you should use. If you need to update your display periodically while you are waiting for something to complete...again, use events. Create a Timer object which generates a TIMER event every so often, and use that to make your updates.
EDIT: Davr is right, you would not be able to use the while loop like this. You would need a timer.
Yes, it is possible to poll for it. BUT you will still need to create an event listener. It will work something like this:
private var loadCompleted = false;
private var timer:Timer= new Timer(1);
private function onInitCompleted(event:Event):void
{
timer.addEventListener(TimerEvent.TIMER, timerHandler);
timer.start();
}
private function loadCompleteEventHandler(event:Event):void
{
loadCompleted = true;
...
}
private function timerHandler()
{
if(!loadCompleted)
{
... // stop the timer or something.
timer.stop();
}
}
Please note, this is VERY BAD code. I would NEVER use it in production because Actionscript is a event driven language. There should be absolutely NO REASON for you to need to do this. Whatever you are trying to do could be accomplished using another method much simpler. Tell me what you are trying to accomplish with this and I will present a better solution.
Sorry for yelling, it's late and I am sleepy.
Doing that means forcing a synchronous model of execution on the underlying asynchronous model (that works with callbacks).
What are you trying to achieve exactly, and why not use a callback?
I agree with the statements about it probably being a bad idea and a while loop will certainly not work this way in ActionScript. However, there may be legitimate reasons for doing what you are attempting to do. Only you can prevent bad code. Instead of judging, I'll just get to an answer for your question.
First I'm going to make an assumption, that what you really want to do is monitor a property and for some reason the API for this object does not dispatch an event when this property changes. I'm making this assumption because if you have the event available, I assume you would just use the event.
So... you have an object weirdXmlObj with a property loaded that defaults to false but goes to true when the XML is loaded.
In this case with slight modifications the code posted by CookieOfFortune would in fact work. You wouldn't need the loadCompleteEventHandler function (which was never attached anyway) and in the timer handler you would simply check if( weirdXmlObj.loaded ) and then branch however you wanted to.
Ah but there may be a simpler way, depending on what you are doing.
If you have a display object handy. (i.e. something that makes sense, not just some random object.) You can attach your code to the stage's EnterFrame event instead of using a timer.
myDisplayObject.stage.addEventListner(Event.ENTER_FRAME,frameEnterHandler);
A couple of things to be aware of:
You don't really even need to go to the stage level, all display objects support the EnterFrame event, but it's a nice place to attach the event listener.
You really should keep whatever the function calls to a minimum. In particular the actual frameEnterHandler function should do nothing more than do the if( weirdXmlObj.loaded ) check.
You are attempting to circumvent event-driven programming, which is not a good idea. This is often the case when someone approaches from an older model and does not yet have a good frame of reference to appreciate the elegance of event-driven programming.
Events are your friends. They work very well. Your loadCompleteHandler is all that is required. Want to do something else in response? Add the call in that handler:
private function loadCompletedHandler(event:Event):void
{
waitingObject.fileWasLoadedSoGoDoThatThing();
}
There is no need to make it any more complicated than that. No need for a semaphore or a loop to check the semaphore. Unnecessary environmental semaphores can break the encapsulation that could shield you from unwanted side effects.

Resources