What's the best practice: to bind or not to bind or do something else?

I have this object.

var ngre  = {
  checkThis: "get this",
  checkAnswer: function(ev){
     // I need access to this.checkThis
     // I need access to the button that triggers me 

In reality the object really big and ngre.checkAnswer needs access to many of the methods within ngre

I have a button which is going to trigger ngre.checkAnswer

<button id="myBtn">click</button>

Now I want to add a click event to the button.

var mybtn = document.getElementById("myBtn");
mybtn.addEventListener("click", ngre.checkAnswer, false);

I’m interested to know what’s the best solution in a realy big project. Which is a better option in terms of performance or anything else

By keeping the binding to the button, I have to do this

var ngre  = {
  checkThis: "get this",
  checkAnswer: function(ev){

I’m not experienced with this but that looks off. The real ngre object is a lot bigger and every time I have to use ngre.checkThis rather than this.checkThis, I feel like I am doing it wrong!

I can use bind

mybtn.addEventListener("click", ngre.checkAnswer.bind(ngre), false);

But I need access to the button that’s being clicked.

It feels obvious not to bind, but what’s the best practice, there might be something I don’t know.

I think either referring to ngre or this is fine, no performance problems there.

checkAnswer may be simpler as a standalone function rather than being attached to that object though, it’s hard to say without seeing the rest of the code but generally I find it easier to separate the data structures from the events.

That’s a great point.

As I developed I had to move towards the same conclusion, not just for ease of use but found that other objects required the use of same data.

This is off topic, but let me ask you this (as with this project I’m trying to learn best practices)

Here is another module I am working on. All the drag and drop methods are binded. But then I have other methods that are used by the binded methods. Should they be separated?

module.exports = function(){
   var movements  = {
        disable: function(){},

	dragstart: function(ev){},
	dragenter: function(ev){},
	dragover: function(ev){},
	drop: function(ev){
 return movements;

I read somewhere that each module should serve a purpose. With that logic, am I right in not separating the drag and drop methods from the methods used within the drag and drop methods?

Again it’s hard giving feedback on a snippet of code without context but It does look awkward to me how you’re putting everything into an object, it doesn’t look like it serves a purpose. It’s possible just to have the functions in the scope of that module refer to each other without the wrapping object.

var disable = function() {};
var drop = function(ev) {

module.exports = {
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.