2013-08-28 5 views
0

У меня есть Dart WebComponent, который периодически получает информацию из веб-службы. Я хотел бы добавить веб-службу в компонент и решить, когда компонент будет вызывать веб-службу (это позволит мне прототипировать весь код пользовательского интерфейса, используя макет веб-службы без HTTP-вызова до тех пор, пока служба не будет написана).КАК-Инициализировать Dart WebComponent

Проблема, с которой я сталкиваюсь, заключается в том, что объект веб-службы, который я отправляю в WebComponent, кажется нулевым, пока страница не будет отображаться. Я не совсем уверен, когда ссылка на службу передается на страницу, но, похоже, это происходит после создания страницы, поскольку значение имеет значение null в конструкторе WebComponent, но я вижу, что это значение создается, когда сама страница оказаны. Как я могу получить уведомление о том, что объект службы теперь доступен для этой страницы, чтобы я мог позвонить в веб-службу?

Следующий вопрос: Проходит ли ссылка на обслуживание в WebComponent, как я ниже плохой практики? Если да, то что я должен сделать вместо того, чтобы отделить макетную реализацию, чтобы позже я мог внедрить реальный веб-сервис без изменения какого-либо кода.

Вот моя база Dart страница:

<!DOCTYPE html> 

<html> 
    <head> 
    <meta charset="utf-8"> 
    <title>Dart Prototype</title> 
    <link rel="stylesheet" href="dart_prototype.css"> 

    <link rel="import" href="location_container.html"> 
    </head> 
    <body> 
    <h1>Dart Prototype</h1> 

    <div id="location_management_container"> 
     <location-container location-service="{{applicationContext.locationService}}" count="{{startingCount}}"></location-container> 
    </div> 

    <script type="application/dart"> 
     import 'package:web_ui/web_ui.dart'; 
     import 'package:dart_prototype/dart_prototype_library.dart'; 

     final ApplicationContext applicationContext = new ApplicationContext(
     new WebService() 
    ); 
     int startingCount = 5; 

     main() { 
     print('main initializing'); 
     print(applicationContext); 
     print(applicationContext.locationService); 
     }  
    </script> 
    <script src="packages/browser/dart.js"></script> 
    </body> 
</html> 

Вот код для location-container

<!DOCTYPE html> 

<html> 
    <head> 
    <meta charset="utf-8"> 
    </head> 
    <body> 
    <element name="location-container"> 
     <template> 
     <div> 
      <ul id="todo-list"> 
      <li>hi there!</li> 
      <li>{{count}}</li> 
      <li>{{locationService}}</li> 
      </ul>   
     </div> 
     </template> 
     <script type="application/dart"> 
     import 'package:web_ui/web_ui.dart'; 
     import 'package:dart_prototype/dart_prototype_library.dart'; 

     class LocationContainer extends WebComponent { 

      @observable 
      WebService locationService; 

      @observable 
      int count; 

      LocationContainer() { 
      print('in loc container constructor'); 
      print(locationService); 
      print(count); 
      }  

      created() { 
      print('created!'); 
      print(locationService); 
      print(count); 
      }    
     }   
     </script> 
    </element> 
    </body> 
</html> 

Вот код для ApplicationContext и WebService

part of prototype_library; 

class ApplicationContext { 

    final WebService locationService; 

    ApplicationContext(
     this.locationService); 

} 

class WebService { 

    final Factory _objectFactory; 

    WebService(this._objectFactory); 

    Future call(String url) { 
    throw new UnimplementedError(); 
    } 
} 

И вот результат моей печати строки на консоль

Invalid CSS property name: -webkit-touch-callout 
main initializing 
Instance of 'ApplicationContext' 
Instance of 'WebService' 
in loc container constructor 
null 
null 
created! 
null 
null 

А вот то, что мои визуализирован страницы:

Dart Prototype 

- hi there! 
- 5 
- Instance of 'WebService' 

И источник этой страницы ...

<!DOCTYPE html> 
<!-- This file was auto-generated from web/dart_prototype.html. --> 
<html><head><style>template { display: none; }</style> 
    <meta charset="utf-8"> 
    <title>Dart Prototype</title> 
    <link rel="stylesheet" href="../dart_prototype.css"> 


    </head> 
    <body> 
    <h1>Dart Prototype</h1> 

    <div id="location_management_container"> 
     <span is="location-container"></span> 
    </div> 


    <script type="application/dart" src="dart_prototype.html_bootstrap.dart"></script><script src="../packages/browser/dart.js"></script> 


</body></html> 

ответ

1

Я думаю, что моя проблема может быть решена с помощью inserted жизненного цикла вместо created.

Первоначально, когда я прочитал WebComponent жизни описание метода цикла, он сказал:

Вызывается всякий раз, когда компонент добавляется в DOM.

Я все еще не уверен, что это правильный способ использования, но у меня есть объект, который я ищу - поэтому я продолжу эксперимент. Вот мое обновление WebComponent

<!DOCTYPE html> 

<html> 
    <head> 
    <meta charset="utf-8"> 
    </head> 
    <body> 
    <element name="location-container"> 
     <template> 
     <div> 
      <ul id="todo-list"> 
      <li>hi there!</li> 
      <li>{{count}}</li> 
      <li>{{locationService}}</li> 
      </ul>   
     </div> 
     </template> 
     <script type="application/dart"> 
     import 'package:web_ui/web_ui.dart'; 
     import 'package:dart_prototype/dart_prototype_library.dart'; 

     class LocationContainer extends WebComponent { 

      @observable 
      WebService locationService; 

      @observable 
      int count; 

      LocationContainer() { 
      print('in loc container constructor'); 
      print(locationService); 
      print(count); 
      }  

      created() { 
      print('created!'); 
      print(locationService); 
      print(count); 
      } 

      inserted() { 
      print('inserted!'); 
      print(locationService); 
      print(count); 
      } 

     }   
     </script> 
    </element> 
    </body> 
</html>