简体   繁体   中英

How do I link <div> to javascript object (without framework)? (Actionscript concepts to JS world)

I'm a relative beginner to Javascript. I come from a background in Flash OOP programming (Actionscript 3), where there was an inherent and explicit relationship between on-screen graphical objects and a Class . I'm trying to figure out if it's possible to translate this direct and explicit relationship to the Javascript/HTML world.

For instance, if I have an online game and had various graphical areas -- a play area, an input area, a scoreboard. I'd like interactions with each of those should be handled by a separate object or prototype (or class or module).

My first thought is to do it through event delegation , adding an event listener to the parent graphical object that covers the area I'm interested in and linking that to a "master method" in the code Object (or Class ) that "represents" that graphical object. From there I could figure out what part of the object was clicked on and reference methods inside the object. This seems an awkward route to go down.

Or I could simply add event listeners to the individual components in the graphical object and them link to event handlers inside the code object which represents that graphical object. I think this is probably the right answer.

I just wanted to ask whether there any other way to link entire graphical DOM objects and entire code Objects (or classes, prototypes, etc), one that more closely mimics that direct connection that Flash offered between one graphical object and one code structure?

In the JavaScript world where there is a web UI to work with, the Document Object Model (DOM) API is your gateway toward connecting JavaScript objects to the HTML elements that make up a page.

While there are many aspects to what the DOM is and can do, it starts with getting a JavaScript reference to a single HTML element (a "node" reference) or to a group of HTML elements (a "node list" reference). We don't make distinctions about whether those elements are "graphical" or not. We think of each of these elements generically, as "nodes". They are part of the HTML document and therefore they are part of a "tree" of elements that we can access.

Getting your references can be done in a variety of ways (the id of the element, the CSS class(es) used by the element(s), the hierarchical position of the element in the larger document structure, etc.).

Here are some examples:

 // Get a DOM node reference via its id var theDiv = document.getElementById("firstDiv"); console.log(theDiv.textContent); // Get a DOM node reference based on its position in the document var theSecondDiv = document.querySelector("#firstDiv + div"); // Sibling following the one with the id console.log(theSecondDiv.textContent); // Get a node list of all the elements that have the "special" class var theSpecials = document.querySelectorAll(".special"); console.log(theSpecials[0].textContent, theSpecials[1].textContent, theSpecials.length); // Get a node reference based on having a certain attribute value var theButton = document.querySelector("input[type='button']"); theButton.value = "I have a new value!"; 
 <div id="firstDiv">I'm a div</div> <div>I'm the second div</div> <p class="special">I'm a paragraph with a class</p> <h2 class="special">I'm an h2 with a class</h2> <input type="button" value="Button"> <input type="text"> 

Once you have your DOM reference, the next step is to interact with the object and this could mean getting/setting property values, calling methods or configuring event callback functions.

For the most part, HTML attributes will map to JavaScript object properties. In the last example the value attribute of the <input type="button"> mapped to the value property of the JavaScript DOM object reference ( theButton.value = ... ). In addition to the attributes of the original HTML element being translated into properties, the DOM API endows DOM object references with additional properties. For example, all nodes have a nodeName , nodeType and nodeValue property and nodes that represent elements that have an opening and closing tag to them will have a .textContent and an .innerHTML property to get/set the content as text or HTML. Other, more unique types of DOM references will have more specific properties.

The DOM API also specifies various methods for DOM objects. Form elements, for example, will have a .focus() method for setting the UI's focus on that element, as if the user had tabbed to the element or clicked into it.

Now, to your question...

Just about all DOM elements support various events and you can configure a single element to respond to one or more events or you can take advantage of "event bubbling" and set an event handler on an ancestor element and wait for events triggered in descendants to bubble up to the ancestor. This is the "event delegation" that you referred to in your question.

Here are examples of both:

 // Set an event handler for the <p> element document.querySelector("p").addEventListener("click", function(){ console.log("You clicked the p"); }); // Event delegation is beneficial in two circumstances. // 1. When a single function should be used to handle the same event for many different elements // and you don't want to have to store that callback function with all the different elements // FYI: all event handlers are automatically passed a reference to the event object that they are handling document.getElementById("parent").addEventListener("click", function(evt){ console.log("The event was handled at the parent, but it was triggered at: " + evt.target); }); // 2. When elements will be dynamically added to the document and you can't statically set up event // handlers for elements that don't exist yet. let span = document.createElement("span"); span.textContent = "I was dynamically created, but if you click me, I'll immediately work!"; document.getElementById("parent").appendChild(span); 
 <div id="parent"> <p>Child One (p)<p> <div>Child Two (div)</div> </div> 

As you can see, event delegation has its place, but unless you have one of the use cases for event delegation, binding individual objects to event handlers is generally the norm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM