-2

Let's say you want to predefine a lot of buttons that are created by a button generator.

function createButton(name, func){
  var btn = '<div class = "button" name = '+name+'/>';
  $('.btn[name = "'+name+'"]').on('click', function(func){});
}

var butn1 = {
  name : "exit",
  func : func1
}

createButton(btn1);

Now if you had 100 buttons, this means a lot of variables. Is that bad? If it is, would this be better?

function chooseButton(name){
 var btn;
 switch(name){
   case "exit":
      btn = {
         name : "exit",
         func : func1
      }
    break;
    case......
  }
 return btn;
}

   var myBtn = chooseButton('exit');
  createButton(myBtn);
user3822370
  • 641
  • 7
  • 20
  • 1
    possible duplicate of [Does creating functions consume more memory](http://stackoverflow.com/questions/7451279/does-creating-functions-consume-more-memory) – Axalo Jan 28 '15 at 03:21
  • 1
    Why should I pretend your code worked when it doesn't? Please don't post wrong code if you try to demonstrate something by it. – Bergi Jan 28 '15 at 03:27
  • It wasn't relevant to the question. – user3822370 Jan 28 '15 at 03:36
  • If you require 100 variables then why would it be bad? What makes you think that 100 `case` statements, that create new objects each time it is run, would be better? (define) – Xotic750 Jan 28 '15 at 03:42
  • I don't know - that's what I am asking. What is the better approach. – user3822370 Jan 28 '15 at 04:03
  • What is your definition of "better"! Provides a greater income, doesn't smell like rotten fish, doesn't have the colour blue in it? Why don't you explain what you want to achieve, along with your current code. If you have working code and you don't have a coding problem then you are asking for a code review and should try http://codereview.stackexchange.com/. – Xotic750 Jan 28 '15 at 08:11

1 Answers1

0

If feel like it would be better to use a more general constructor for this sort of thing, assuming I've understood your question.

HTML

<div id="buttonContainer">
    <button class="btn btn-type-a">Type A Button</button>
    <button class="btn btn-type-b">Type B Button</button>
    <!-- add further types -->
</div>

JS

var _functs = {
    typeA: function () { alert('type A funct'); },
    typeB: function () { alert('type B funct'); }
};

var _buttons = document.getElementById('buttonContainer')[0].childNodes;

for (var _i = 0; _i < _buttons.length; _i++) {
    if (_buttons[_i].classList.contains('btn-type-a')) {
        /* 
         node.classList.contains (not supported by IE < 10)
         $(_buttons[_i]).hasClass('btn-type-a') if you're using jQuery
        */
        _buttons[_i].addEventListener('click', _functs.typeA, false);
    }
    // other logic for other button assignment
};
lindsay
  • 972
  • 2
  • 11
  • 21