• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "sync/js/sync_js_controller.h"
6 
7 #include "base/location.h"
8 #include "sync/js/js_backend.h"
9 #include "sync/js/js_event_details.h"
10 
11 namespace syncer {
12 
SyncJsController()13 SyncJsController::SyncJsController() {}
14 
~SyncJsController()15 SyncJsController::~SyncJsController() {
16   AttachJsBackend(WeakHandle<JsBackend>());
17 }
18 
AddJsEventHandler(JsEventHandler * event_handler)19 void SyncJsController::AddJsEventHandler(JsEventHandler* event_handler) {
20   js_event_handlers_.AddObserver(event_handler);
21   UpdateBackendEventHandler();
22 }
23 
RemoveJsEventHandler(JsEventHandler * event_handler)24 void SyncJsController::RemoveJsEventHandler(JsEventHandler* event_handler) {
25   js_event_handlers_.RemoveObserver(event_handler);
26   UpdateBackendEventHandler();
27 }
28 
AttachJsBackend(const WeakHandle<JsBackend> & js_backend)29 void SyncJsController::AttachJsBackend(
30     const WeakHandle<JsBackend>& js_backend) {
31   js_backend_ = js_backend;
32   UpdateBackendEventHandler();
33 }
34 
HandleJsEvent(const std::string & name,const JsEventDetails & details)35 void SyncJsController::HandleJsEvent(const std::string& name,
36                                      const JsEventDetails& details) {
37   FOR_EACH_OBSERVER(JsEventHandler, js_event_handlers_,
38                     HandleJsEvent(name, details));
39 }
40 
UpdateBackendEventHandler()41 void SyncJsController::UpdateBackendEventHandler() {
42   if (js_backend_.IsInitialized()) {
43     // To avoid making the backend send useless events, we clear the
44     // event handler we pass to it if we don't have any event
45     // handlers.
46     WeakHandle<JsEventHandler> backend_event_handler =
47         js_event_handlers_.might_have_observers() ?
48         MakeWeakHandle(AsWeakPtr()) : WeakHandle<SyncJsController>();
49     js_backend_.Call(FROM_HERE, &JsBackend::SetJsEventHandler,
50                      backend_event_handler);
51   }
52 }
53 
54 }  // namespace syncer
55