A apresentação está carregando. Por favor, espere

A apresentação está carregando. Por favor, espere

Programação na Internet Secção de Programação ISEL-DEETC-LEIC Carlos Guedes – Paulo Pereira –

Apresentações semelhantes


Apresentação em tema: "Programação na Internet Secção de Programação ISEL-DEETC-LEIC Carlos Guedes – Paulo Pereira –"— Transcrição da apresentação:

1 Programação na Internet Secção de Programação ISEL-DEETC-LEIC Carlos Guedes – cguedes@cc.isel.ipl.ptcguedes@cc.isel.ipl.pt Paulo Pereira – palbp@cc.isel.ipl.ptpalbp@cc.isel.ipl.pt Document Object Model (DOM)

2 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 2 Autores e contributos Autores –Luís Falcão Contributos –Paulo Pereira –Pedro Félix –Jorge Martins –Carlos Guedes –Nuno Datia 2

3 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 3 Document Object Model (DOM) DOM – Introdução API para acesso aos elementos de um documento HTML e XML, bem formado (well-formed). Define a estrutura lógica dos documentos e a forma de acesso e manipulação. O DOM permite: –Criar documentos –Navegar através da sua estrutura –Adicionar, remover e modificar elementos e o seu conteúdo –Aceder a todo (com algumas excepções, por enquanto) o conteúdo de um documento (HTML e XML) A especificação DOM define uma interface independente de qualquer linguagem e plataforma (definida em IDL da OMG, definido no CORBA 2.2). URL da especificação DOM: http://www.w3.org/DOM/

4 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 4 Document Object Model (DOM) Características básicas do DOM 1.O modelo de objectos é independente de qualquer linguagem e plataforma. 2.Existência de uma interface base no DOM que é aplicável a documentos HTML, CSS e XML. 3.O modelo de objectos pode ser utilizado para construir e destruir um documento. 4.Não exclui a possibilidade de utilização do modelo de objectos por agentes externos ao documento, ou a script embebido no documento. 5.Utilização de convenções de nomes entre os vários níveis de DOM. 6.Uma implementação DOM não necessita de criar componentes visuais. 7.Os objectos específicos para documentos HTML, CSS e XML são definidos pelos elementos dessas linguagens. 8.Permitir ler um documento e criar outro com a mesma estrutura. 9.Não expõe o utilizador a problemas relacionados com segurança, validade, ou privacidade. 10.Não exclui a possibilidade de existência de outros mecanismos para manipular os documentos.

5 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 5 Document Object Model (DOM) Níveis de DOM Actividades iniciadas em Agosto de 1997. A especificação DOM foi dividida em vários níveis (actualmente 3). Cada nível trata de um conjunto de funcionalidades. Os níveis 1, 2 e 3 já são recomendações. O DOM Working Group não é o único do W3C que produz APIs e extensões à arquitectura DOM. Outros módulos do DOM incluem: DOM para MathML 2.0: API genérica para documentos MathML 2.0. DOM para animações SMIL (Synchronized Multimedia Integration Language): API genérica para animações SMIL. DOM para SVG 1.0: API genérica para documentos SVG 1.0.

6 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 6 Document Object Model (DOM) Arquitectura DOM A arquitectura do DOM está dividida em módulos. Cada módulo endereça um domínio específico. Os domínios cobertos actualmente API DOM são: –DOM Core –DOM XML –DOM HTML –DOM Events –DOM CSS –DOM Load and Save –DOM Validation –DOM XPath

7 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 7 Document Object Model (DOM) DOM Nível 1 DOM Nível1 (especificação desde Outubro de 1998)DOM Nível1 –Navegação sobre a estrutura do documento –Manipulação do documento –Manipulação do conteúdo

8 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 8 Document Object Model (DOM) DOM Nível 2 DOM Nível2 (recomendação desde Novembro de 2000 ) –Extensões ao nível 1 para suportar XML 1.0 Namespaces (Document Object Model Level 2 Core )Document Object Model Level 2 Core –Modelo de objectos para as Cascading StyleSheets (Document Object Model Level 2 Style)Document Object Model Level 2 Style –Modelo de eventos para user interfaces e de manipulação do documento (Document Object Model Level 2 Events)Document Object Model Level 2 Events –Possibilidade de ter visão linear e filtrada um documento (Document Object Model Level 2 Traversal and Range)Document Object Model Level 2 Traversal and Range –Especificação baseada no DOM Nível 2 Core e não compatível com a DOM Nível 1 HTML (Document Object Model Level 2 HTML)Document Object Model Level 2 HTML –Manipulação do aspecto visual de um documento (Document Object Model Level 2 Views)Document Object Model Level 2 Views

9 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 9 Document Object Model (DOM) DOM Nível 2 - Arquitectura

10 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 10 Document Object Model (DOM) DOM Nível 3 DOM Nível3 (já é uma recomendação) –Extensões ao nível 2 para suporte total dos Namespaces XML 1.0 (Document Object Model Level 3 Core)Document Object Model Level 3 Core –Load and Save (Document Object Model Level 3 Load and Save)Document Object Model Level 3 Load and Save –Validações (Document Object Model Level 3 Validation)Document Object Model Level 3 Validation –Eventos (Document Object Model Level 3 Events)Document Object Model Level 3 Events –XPath (Document Object Model Level 3 XPath)Document Object Model Level 3 XPath

11 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 11 Document Object Model (DOM) DOM Nível 3 Arquitectura

12 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 12 Document Object Model (DOM) DOM Nível 3 Arquitectura (final)

13 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 13 Document Object Model (DOM) DOM – O que é? Shady Grove Aeolian Over the River, Charlie Dorian API para acesso ao conteúdo de um documento. Estrutura de objectos que espelha a estrutura do documento original. O modelo de objectos DOM define: –As interfaces e os objectos utilizados para representar os elementos de um documento. –A semântica dessas interfaces. –As relações e colaborações entre interfaces e objectos.

14 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 14 Document Object Model (DOM) DOM – O que não é? Embora fortemente influenciado pelo “Dynamic HTML Object Model” (DOM Nível 0), não implementa toda a sua funcionalidade no Nível 1. Não é uma especificação binária (tipo COM ou CORBA). Tem que ser feita uma adaptação (mapeamento) para cada linguagem. Não define como é que objectos são representados em XML ou HTML. Em vez disso define como é que documentos HTML e XML são representados na forma de objectos. Não é um conjunto de estruturas de dados. É um modelo de objectos que define interfaces. A API define apenas relações lógicas entre interfaces, não sugerindo nenhuma estrutura física para a implementação. Não define qual a informação que é relevante num documento, nem como esta deve ser estruturada. Não é um competidor do COM ou CORBA. Pode ser implementado utilizando qualquer um destes sistemas de objectos (ou não).

15 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 15 Document Object Model (DOM) Tipos e interfaces Básicas (1) typedef sequence DOMString; exception DOMException { unsigned short code; }; // ExceptionCode const unsigned short INDEX_SIZE_ERR = 1; const unsigned short DOMSTRING_SIZE_ERR = 2; const unsigned short HIERARCHY_REQUEST_ERR = 3; const unsigned short WRONG_DOCUMENT_ERR = 4; const unsigned short INVALID_CHARACTER_ERR = 5; const unsigned short NO_DATA_ALLOWED_ERR = 6; const unsigned short NO_MODIFICATION_ALLOWED_ERR = 7; const unsigned short NOT_FOUND_ERR = 8; const unsigned short NOT_SUPPORTED_ERR = 9; const unsigned short INUSE_ATTRIBUTE_ERR = 10; interface DOMImplementation { boolean hasFeature( in DOMString feature, in DOMString version); }; interface DocumentFragment : Node { }; DOMString DOMException DOMImplementation DOMFragment

16 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 16 Document Object Model (DOM) Interface Document interface Document : Node { // Attributes readonly attribute DocumentType doctype; readonly attribute DOMImplementation implementation; readonly attribute Element documentElement; // Methods Element createElement(in DOMString tagName) raises(DOMException); DocumentFragment createDocumentFragment(); Text createTextNode(in DOMString data); Comment createComment(in DOMString data); CDATASection createCDATASection(in DOMString data) raises(DOMException); ProcessingInstruction createProcessingInstruction(in DOMString target, in DOMString data) raises(DOMException); Attr createAttribute(in DOMString name) raises(DOMException); EntityReference createEntityReference(in DOMString name) raises(DOMException); Element getElementById(in DOMString idname); // DOM Level 2 NodeList getElementsByTagName(in DOMString tagname); }; Node Document Document

17 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 17 Document Object Model (DOM) Interface Node - Constantes interface Node { // Constants // NodeType const unsigned short ELEMENT_NODE = 1; const unsigned short ATTRIBUTE_NODE = 2; const unsigned short TEXT_NODE = 3; const unsigned short CDATA_SECTION_NODE = 4; const unsigned short ENTITY_REFERENCE_NODE = 5; const unsigned short ENTITY_NODE = 6; const unsigned short PROCESSING_INSTRUCTION_NODE = 7; const unsigned short COMMENT_NODE = 8; const unsigned short DOCUMENT_NODE = 9; const unsigned short DOCUMENT_TYPE_NODE = 10; const unsigned short DOCUMENT_FRAGMENT_NODE = 11; const unsigned short NOTATION_NODE = 12;... }; Node Node

18 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 18 Document Object Model (DOM) Interface Node - Atributos interface Node {... // Attributes readonly attribute unsigned short nodeType; readonly attribute Node parentNode; readonly attribute NodeList childNodes; readonly attribute Node firstChild; readonly attribute Node lastChild; readonly attribute Node previousSibling; readonly attribute Node nextSibling; readonly attribute Document ownerDocument; readonly attribute DOMString nodeName; attribute DOMString nodeValue; readonly attribute NamedNodeMap attributes; }; Valores de nodeName, nodeValue e attributes, consoante o tipo de elemento Node

19 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 19 Document Object Model (DOM) Interface Node - Métodos interface Node {... // Methods Node insertBefore(in Node newChild, in Node refChild) raises(DOMException); Node replaceChild(in Node newChild, in Node oldChild) raises(DOMException); Node removeChild(in Node oldChild) raises(DOMException); Node appendChild(in Node newChild) raises(DOMException); boolean hasChildNodes(); Node cloneNode(in boolean deep) raises(DOMException); }; Node

20 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 20 Document Object Model (DOM) Interfaces NodeList e NamedNodeMap interface NodeList { // Attributes readonly attribute unsigned long length; // Methods Node item(in unsigned long index);// x[index] }; interface NamedNodeMap { // Attributes readonly attribute unsigned long length; // Methods Node getNamedItem(in DOMString name); Node setNamedItem(in Node arg) raises(DOMException); Node removeNamedItem(in DOMString name) raises(DOMException); Node item(in unsigned long index); // x[index] }; NodeList NamedNodeMap

21 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 21 Document Object Model (DOM) Interface Attr interface Attr : Node { readonly attribute DOMString name; readonly attribute boolean specified; // Modified in DOM Level 1: attribute DOMString value; }; Node Attr Attr

22 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 22 Document Object Model (DOM) Interface Element interface Element : Node { readonly attribute DOMString tagName; DOMString getAttribute(in DOMString name); void setAttribute(in DOMString name, in DOMString value) raises(DOMException); void removeAttribute(in DOMString name) raises(DOMException); Attr getAttributeNode(in DOMString name); Attr setAttributeNode(in Attr newAttr) raises(DOMException); Attr removeAttributeNode(in Attr oldAttr) raises(DOMException); NodeList getElementsByTagName(in DOMString name); // * means all Tags void normalize(); }; Node Element Element

23 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 23 Document Object Model (DOM) Interface CharacterData interface CharacterData : Node { attribute DOMString data; // raises(DOMException) on setting and retrieval readonly attribute unsigned long length; DOMString substringData(in unsigned long offset, in unsigned long count) raises(DOMException); void appendData(in DOMString arg) raises(DOMException); void insertData(in unsigned long offset, in DOMString arg) raises(DOMException); void deleteData(in unsigned long offset, in unsigned long count) raises(DOMException); void replaceData(in unsigned long offset, in unsigned long count, in DOMString arg) raises(DOMException); }; Node CharacterData CharacterData

24 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 24 Document Object Model (DOM) Interfaces Text e Comment interface Text : CharacterData { Text splitText(in unsigned long offset) raises(DOMException); }; Text Node CharacterData Comment interface Comment : CharacterData { }; Text Comment

25 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 25 Document Object Model (DOM) Interfaces DOM para HTML Extensões às interfaces básicas DOM, específicas para documentos HTML. Na interface básica, são disponibilizadas todas as funcionalidades que permitem: –Manipulação da estrutura hierárquica dos documentos. –Manipulação de elementos. –Manipulação de atributos. Na interface DOM para HTML são disponibilizadas funcionalidades que dependem das especificidades dos elementos do HTML. Os objectivos desta API são: –Especialização de funcionalidades relacionadas com os elementos HTML. –Manutenção de compatibilidade com DOM Nível 0 (DHTML). –Oferecer mecanismos para implementar as operações mais frequentes sobre documentos HTML (sempre que se justifique). Esta API não é obrigatória, numa implementação DOM nível 1. Caso a implementação suporte estas interfaces, deve responder true no método hasFeature de DOMImplementation, quando recebe como parâmetros as strings “HTML” e “1.0”.

26 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 26 Document Object Model (DOM) Interface HTMLCollection interface HTMLCollection { readonly attribute unsigned long length; Node item(in unsigned long index); // nodeName corresponds to HTML attribute “id” or “name” Node namedItem(in DOMString nodeName); }; HTMLCollection

27 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 27 Document Object Model (DOM) Interface HTMLDocument interface HTMLDocument : Document { attribute DOMString title; readonly attribute DOMString referrer; readonly attribute DOMString domain; readonly attribute DOMString URL; attribute HTMLElement body; readonly attribute HTMLCollection images; readonly attribute HTMLCollection applets; readonly attribute HTMLCollection links; readonly attribute HTMLCollection forms; readonly attribute HTMLCollection anchors; attribute DOMString cookie; void open(); void close(); void write(in DOMString text); void writeln(in DOMString text); Element getElementById(in DOMString elementId); NodeList getElementsByName(in DOMString elementName); }; Node Document HTMLDocument HTMLDocument

28 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 28 Document Object Model (DOM) Interface HTMLElement Elementos HTML que apenas disponibilizam a interface básica HTMLElement : –HEAD –special: SUB, SUP, SPAN, BDO –font: TT, I, B, U, S, STRIKE, BIG, SMALL –phrase: EM, STRONG, DFN, CODE, SAMP, KBD, VAR, CITE, ACRONYM, ABBR –list: DD, DT –NOFRAMES, NOSCRIPT –ADDRESS, CENTER interface HTMLElement : Element { attribute DOMString id; attribute DOMString title; attribute DOMString lang; attribute DOMString dir; attribute DOMString className; }; Node Element HTMLElement HTMLElement

29 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 29 Document Object Model (DOM) Interfaces para outros elementos do HTML Node Element HTMLElement HTMLHtmlElement HTMLHeadElement HTMLTitleElement HTMLMetaElement HTMLBaseElementHTMLStyleElement HTMLBodyElement HTMLFormElement HTMLLinkElement

30 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 30 DOM 2 – Modelo de Eventos Sistema de eventos genérico que –Permite o registo de handlers de eventos –Fornece conjuntos de eventos para a controlo da UI e para notificação da alteração da estrutura do documento –Define a informação contextual para cada um dos tipos de eventos –Contém como subconjunto, os eventos utilizados no DOM nível 0 Existem várias técnicas possíveis para gerir a captura de eventos É possível a um evento ser capturado ao longo de um caminho na árvore DOM

31 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 31 Event Flow Existem duas fases no processamento de eventos: –Capture – A primeira das fases, onde o evento percorre a árvore do documento, desde a raiz até ao elemento a que é destinado o evento –Bubble – Processo contrário, onde o evento depois de processado pelo elemento a que se destinava, é passado para o nó pai, afim de ser processado Capture Bubbling

32 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 32 Interfaces de registo de Eventos EventTarget interface CharacterData : Node { void addEventListener(in DOMString type, in EventListener listener, in boolean useCapture); void removeEventListener(in DOMString type, in EventListener listener, in boolean useCapture); boolean dispatchEvent(in Event evt) raises(EventException); }; EventListener interface EventListener { void handleEvent(in Event evt); };

33 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 33 Registo de Handlers O registo de handlers é efectuado sobre o objecto “gerador” de eventos: –node.["on" + type] = f; –node.addEventListener(type, f, false); –Nos browsers que não implementam o especificação DOM nível 2 para eventos (e.g. Microsoft ie), a forma de registo anterior não funciona Atenção! window.onload = function () { alert(“página carregada!”);} Da forma clássica window.addEventListener(“load”, function () { alert(“página carregada!”);}, false); W3C DOM

34 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 34 Captura de Eventos No registo dos handlers, é possível especificar se é pretendido capturar o evento antes de ele ser processado pelo nó destinatário div.addEventListener(“click”, function () { alert(“página carregada!”);}, true); Qualquer evento que seja gerado no nó ou em algum dos seus descendentes, é, em primeiro lugar, notificado o nó Só depois serão notificados os nós descendentes (que tiverem capturado o evento) e finalmente o nó destinatário 1 2

35 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 35 Bubbling Uma vez processado o evento pelo nó destinatário, são evocados os handlers dos nós ascendentes, pela ordem inversa da fase anterior (captura) div.addEventListener(“click”, function () { alert(“página carregada!”);}, false); É possível evitar que o evento seja propagado para os ascendentes – evocando o método stopPropagation Note-se que nem todos os eventos suportam bubbling (e.g load) e nem todos podem ser cancelados (e.g. mousemove ) 3 2

36 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 36 Interface Evento Event interface // PhaseType const unsigned short CAPTURING_PHASE = 1; const unsigned short AT_TARGET = 2; const unsigned short BUBBLING_PHASE = 3; readonly attribute DOMString type; readonly attribute EventTarget target; readonly attribute EventTarget currentTarget; readonly attribute unsigned short eventPhase; readonly attribute boolean bubbles; readonly attribute boolean cancelable; readonly attribute DOMTimeStamp timeStamp; void stopPropagation(); void preventDefault(); void initEvent(in DOMString eventTypeArg, in boolean canBubbleArg, in boolean cancelableArg);};

37 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 37 Handlers e eventos De acordo com a especificação DOM, é sempre passado como parâmetro ao handler o evento –Atenção!!! Nos browsers da Microsoft não é passado nenhum evento como parâmetro – tem de ser consultado o objecto global window.event

38 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 38 Eventos DOM Na especificação DOM nível 2, estão definidos 3 tipos de eventos: –Eventos da User Interface e.g. DomFocusIn –Eventos de rato e.g. click –Eventos de alteração da estrutura do documento (Mutation Events) e.g. DOMNodeInserted A especificação DOM nível três define também eventos de teclado Event UIEvent MouseEvent MutationEvent

39 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 39 Eventos de Rato Os eventos de rato são aqueles que são mais utilizados: –click, mousedown, mouseup, mouseover, mouseout, mousemove Quando são deste tipo, os eventos contêm também as propriedades: PropriedadeDescrição altKey, ctrlKey, metaKey, shiftKey true, quando a tecla estava premida no momento da ocorrência do evento button Um inteiro que indica qual dos botões do rato foi premido: 1 = left, 2 = middle, 3 = right. relatedTarget MouseEnter e MouseLeave screenX, screenY A coordenada do ponteiro do rato relativa ao ecrã clientX, clientY A coordenada do ponteiro do rato relativa à área de cliente (e.g browser)

40 2007 - 2011 ©ISEL/DEETC/SP – Programação na Internet 40 Bibliografia W3C Document Object Model (http://www.w3.org/DOM/)http://www.w3.org/DOM/ Dom Technical Reports (http://www.w3.org/DOM/DOMTR)


Carregar ppt "Programação na Internet Secção de Programação ISEL-DEETC-LEIC Carlos Guedes – Paulo Pereira –"

Apresentações semelhantes


Anúncios Google