Confirmed users
130
edits
(Add bug query for labeling bugs so people can find something to do to help) |
Wmccloskey (talk | contribs) (change script loader example to avoid null docgroup issue) |
||
| Line 48: | Line 48: | ||
+ Dispatch("UpdateVisibility", TaskCategory::Other, event.forget()); | + Dispatch("UpdateVisibility", TaskCategory::Other, event.forget()); | ||
} | } | ||
== Event Targets == | == Event Targets == | ||
| Line 114: | Line 79: | ||
aName.AssignLiteral("XMLHttpRequest"); | aName.AssignLiteral("XMLHttpRequest"); | ||
return NS_OK; | return NS_OK; | ||
} | |||
=== Script loader example === | |||
As a more complex example, consider off-thread script parsing. When parsing is done, a NotifyOffThreadScriptLoadCompletedRunnable runnable is posted to the main thread. We can modify this code to save an event target while still on the main thread, storing it in the runnable, and then dispatching to that event target off the main thread: | |||
class NotifyOffThreadScriptLoadCompletedRunnable : public Runnable | |||
{ | |||
RefPtr<nsScriptLoadRequest> mRequest; | |||
RefPtr<nsScriptLoader> mLoader; | |||
+ nsCOMPtr<nsIEventTarget> mEventTarget; | |||
void *mToken; | |||
public: | |||
NotifyOffThreadScriptLoadCompletedRunnable(nsScriptLoadRequest* aRequest, | |||
nsScriptLoader* aLoader) | |||
: mRequest(aRequest) | |||
, mLoader(aLoader) | |||
+ , mEventTarget(aLoader->GetEventTarget()) | |||
{ MOZ_ASSERT(NS_IsMainThread(); } | |||
... | |||
} | |||
For this to work, we need to instrument the nsScriptLoader with an EventTarget method. That's very easy though: | |||
nsIEventTarget* | |||
nsScriptLoader::GetEventTarget() const | |||
{ | |||
return mDocument->EventTargetFor(TaskCategory::Other); | |||
} | |||
Finally, when dispatching, we use the event target. Note that we need to set the runnable name manually: | |||
static void Dispatch(already_AddRefed<NotifyOffThreadScriptLoadCompletedRunnable>&& aSelf) { | |||
RefPtr<NotifyOffThreadScriptLoadCompletedRunnable> self = aSelf; | |||
nsCOMPtr<nsIEventTarget> target = self->mEventTarget; | |||
self->SetName("NotifyOffThreadScriptLoadCompletedRunnable"); | |||
target->Dispatch(self.forget(), DISPATCH_NORMAL); | |||
} | } | ||