简体   繁体   中英

How do I add a variable (string) - to an existing object?

I have an object

this.ui.list
this.ui.grid

These points to a Node element on the DOM already

At the moment, I have two buttons, 'Grid', 'List'. Grid has a class Active by default, and List doesn't. I have a click event listener on both, and when you click on Grid, it should remove the class Active, and add it to the other sibling, List.

ex. If clicked on grid

let siblingElement = utils.js.func.siblings(el.target), // list node
    siblingStyle = siblingElement[0].dataset.style, // outputs: list
    currentElement = el.target, // grid node
    currentStyle = el.target.dataset.style // outputs: grid


classes.remove(siblingElement[0], 'active')
classes.add(el.target, 'active')

This works fine, now what I have to do is fade in/out the dom elements that displays the list/grid.

Since when I click on grid for example, I can get the word list by checking the sibling data attribute, I wanted to dynamically use these below to avoid copy/paste, and avoid using if/else/switch

tl.to(this.ui.grid, 0.7, { autoAlpha: 0, display: 'none', ease: Expo.easeInOut })
tl.to(this.ui.list, 0.7, { autoAlpha: 1, display: 'block', ease: Expo.easeInout })

Since I can get the current style, and the sibling style....'list', 'grid', how would it be able to replace this.ui.grid, this.ui.list with the variables I set above? I hope this isn't confusing, but basically something like this ( I know this does not work )

tl.to(this.ui.[siblingStyle], 0.7, { autoAlpha: 0, display: 'none', ease: Expo.easeInOut })
tl.to(this.ui.[currentStyle], 0.7, { autoAlpha: 1, display: 'block', ease: Expo.easeInout })

Is this even possible with Javascript?

So, after some thinking....I finally just decided to go with this solution. If there is something better, please let me know.

var choices = {
    "list" : this.ui.grid,
    "grid" : this.ui.list
}

// Fade Effect
tl.to(choices[currentStyle], 0.7, { autoAlpha: 0, display: 'none', ease: Expo.easeInOut })
tl.to(choices[siblingStyle], 0.7, { autoAlpha: 1, display: 'block', ease: Expo.easeInout })

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