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.

Community
  • 1
  • 1
cheng
  • 1,264
  • 2
  • 18
  • 41
  • So this question doesn't have a specific issue, this is purely opinion based? – NewToJS Oct 11 '16 at 09:13
  • @NewToJS the issue is how to apply good practice to solve this problem – cheng Oct 11 '16 at 09:25
  • Related: [Javascript DOM: Setting custom DOM element properties](https://stackoverflow.com/questions/7895560/javascript-dom-setting-custom-dom-element-properties), [Adding custom ( your own ) properties to DOM objects, OK?](https://stackoverflow.com/questions/24843865/adding-custom-your-own-properties-to-dom-objects-ok), [Is it bad practice to add properties to DOM nodes?](https://stackoverflow.com/questions/3095336/is-it-bad-practice-to-add-properties-to-dom-nodes) – Felix Kling May 02 '19 at 18:58
  • Sounds like you want something like [React JSX](https://reactjs.org/docs/introducing-jsx.html) – zer00ne May 02 '19 at 20:00

1 Answers1

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).

Chris Ferdinandi
  • 1,892
  • 4
  • 26
  • 34