2

so this is mainly a question of best Javascript practices. I'm creating a library with vanilla JS for an alarm clock.

It goes something like:

HTML

<div>current time</div>
<form> ... </form>         <!-- create new alarm -->
<ul id="alarms"></ul>

JS

 // init variables to select DOM elements
 var Alarm = function() {
   // has a ring function, private vars for name, ringtone, time, isActive
 }
 var AlarmClock = function() {
    var alarms = []
    this.createAlarm = function() {
      // creates Alarm and pushes it to alarms array
      // also creates Alarm DOM element to append to the <ul>
    }
 }

I definitely feel that it is redundant to create both a DOM element and a Javascript Object for an Alarm so I'm wondering if it's possible to incorporate them into one method? I'm thinking that we can just push the DOM Elements to the alarms array in the AlarmClock class so that when I implement alarm deletion, I can just splice the array and the DOM objects would disappear.

Or if there's some way to bind an HTML DOM Element to the Javascript class. I looked at this which suggests using jQuery data() but I want to accomplish it with vanilla JS. I was thinking I could also just add a property to an Alarm object that references the corresponding DOM element but I'd love to hear some experienced programmers chime in on what the best practices would be.

4

1 Answer 1

0

From an article I wrote on objects in JavaScript:

In JavaScript, everything is an object, even when it’s something else. Functions are objects. Strings are objects. Numbers are objects. Arrays are objects. Objects are objects. As a result, anything can have properties assigned to it.

That means that yes, you can assign those properties directly to a DOM node (or more specifically, the JS variable you have it cached to).

Sign up to request clarification or add additional context in comments.

1 Comment

But DOM nodes are also host objects so they may not behave like "normal" objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.