-1

I am very new to this and it is reflected on the way i put the title.

May be the example below can illustrate my question better.

I have a an object called model.

var Modal = new function(){
    this.id = 'modal_id';
    this.title = 'Modal title';
    this.content = 'Modal content';
    this.display = function(){
        return '<div class="popup">' + this.title + ' ' + this.content + '<br><button id="button"></div>';
    };
}

The object is called with this for example:

Modal.title = 'My New title';
Modal.content = 'My New content';
Modal.display();

But let's say i want to have an event for the button the trigger different action, how can i define the function when calling the object when button is clicked?

$('#button').on('click', function(){
    // different action here
});
esqew
  • 42,425
  • 27
  • 92
  • 132
davidlee
  • 5,611
  • 17
  • 56
  • 82
  • what are you trying to call when its clicked? Modal.display()? – Event_Horizon Aug 13 '14 at 15:47
  • It can be any action. but i want such a way that i can have custom action for that click and can be defined when calling it. One Modal can trigger action A while another Modal can trigger another different action when the button is clicked. – davidlee Aug 13 '14 at 15:50
  • [Don't ever use `new function() { … }`!](http://stackoverflow.com/q/10406552/1048572) – Bergi Aug 13 '14 at 16:00
  • Can you give me a valid reason? @Bergi – davidlee Aug 13 '14 at 16:14
  • @davidlee: Please read the answers to the question I linked to. If you have any objections to the reasons I gave there, please comment there. – Bergi Aug 13 '14 at 16:25

1 Answers1

1

There are two things that you should do to make this work the best.

  • Pass in a function to be assigned
  • Return a real DOM element instead of messing about with building HTML from strings.

    var Modal = function(onClickHandler){
      this.id = 'modal_id';
      this.title = 'Modal title';
      this.content = 'Modal content';
      this.display = function(){
          var div = document.createElement("div");
          div.className = "popup";
          div.appendChild(document.createTextNode(this.title));
          div.appendChild(document.createTextNode(" "));
          div.appendChild(document.createTextNode(this.content));
          div.appendChild(document.createElement("br");
    
          var button = document.createElement("button");
          // Assign a unique ID here if you need.
    
          // You could also use addEventListener as well
          button.onclick = onClickHandler;
          button.appendChild(document.createTextNode("CLICK!"));
    
    
          div.appendChild(button);
          return div;
      };
    }
    
    Modal.prototype.close = function(){
      console.log("Close it");
      console.log(this);
    }
    
    
    var newDiv = new Modal(function() {
      alert("I was clicked");
    });
    
Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74