Passing Object in es6 Template string

1.9k Views Asked by At

I have this below code segment

${res.result.map(resultObj =>
`<div class="col-sm-4 mb-4">
   <a class="btn btn-primary" onclick="getEditable(resultObj)">Edit</a>
 </div>`
)};


window.getEditable = (resultObj) => {
  console.log(resultObj);
}

This throws error "results" is not defined. How should I pass the results object to a function using Template String ?

Also would like to ask is using window. is a good approach ?

Help would be appreciated

2

There are 2 best solutions below

5
On BEST ANSWER

It seems as though you're looking to be able to have html reflect the state of an object which may change, and that normally means being able to watch that state in some way. This often means using a library/framework, like React, or Vue, as doing this kind of reactivity is not easy once a project gets beyond a trivial size.


Here's a minimal example to demonstrate the problem:

const el = document.getElementById('output')

const values = [
  {
    id: 1
  },
  {
    id: 2
  },
]

const log = text => {
  console.log(text)
}

el.innerHTML = values.map(valueIter => `
  <button onclick="log(valueIter)">
    ${valueIter.id}
  </button>
`);
<button onclick="log(valueIter)">Test Button</button>
<div id="output"></div>

In the above example, the text valueIter gets put into the onclick function call, the the actual object which is part of the map call. Replacing this with ${valueIter.id} would instead pass the text of the valueIter's id property. If this changes, though, we would still get the original value.

An alternative would be to access the actual value which is to be logged:

const el = document.getElementById('output')

const values = [
  {
    id: 1
  },
  {
    id: 2
  },
]

const log = text => console.log(text)

el.innerHTML = values.map((value, i) => `
  <button onclick="log(values[${i}])">
    ${value.id}
  </button>
`)

values[0] = {
  id: 99
}
<div id="output"></div>

You'll notice that the text of the button doesn't change. There's nothing in this code to force the DOM to update once the original value changes, which is where things get quite a bit more complex. There's essentially nothing binding the output of the DOM to the state of the object it is supposed to be rendering.

1
On

You can use id

res.result.map(results =>
  `<div class="col-sm-4 mb-4">
    <a class="btn btn-primary" onclick="getEditable(${results.id})">Edit</a>
  </div>`
);

var getEditable = id => {
  var resultObj = res.result.find(elem => {
    return elem.id == id;
  });
  console.log(resultObj);
}

Also would like to ask is using window. is a good approach ?

Using window object in this case is a bad practice