0
var events = {
                addEvent: function(element, type, fn, capture){
                     element.addEventListener(type, fn, capture);
                },
                removeEvent: function(){
                     element.removeEventListener(type, fn, capture);
                }
           }

I'm loking for something like this in object literal definition to reduce the code the event Object is just an example

           var events = {
                            [action + "Event"]: function(element, type, fn, capture){
                                  element[action + "eventListener"](type, fn, capture);
                        }
                }
           }

I know there are other options like

element.events.add(....) , element.events.remove(....)

or this option

element.events("add", type, fn, capture) / element.events("remove", type, fn, capture)
zEn feeLo
  • 1,877
  • 4
  • 25
  • 45

1 Answers1

1

Property names in object initializers must be constants. You can however add properties to an object and create names dynamically:

var events = {
            addEvent: function(element, type, fn, capture){
                 element.addEventListener(type, fn, capture);
            },
            removeEvent: function(){
                 element.removeEventListener(type, fn, capture);
            }
       };

events[action + "Event"] = function() { /* ... */ };
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • u mean first create an empty object and then with bracket notation define a function ? – zEn feeLo Dec 28 '14 at 14:00
  • @CameronA yes - you can add all the properties you want after the object is created. However, in the object initializer itself, the property names must be constants. – Pointy Dec 28 '14 at 14:05
  • 1
    EcmaScript 6 has something called Computed Property Name and it is exactly what I'm looking for – zEn feeLo Dec 28 '14 at 16:06
  • @CameronA yes that's true! In ES6 things are more flexible. – Pointy Dec 28 '14 at 16:06