Skip to content

Add model to htmlwidget #28

@timelyportfolio

Description

@timelyportfolio

I think this is fairly harmless and will not cause negative side effects. Could we add model to the htmlwidget so that it is accessible through the HTMLWidgets.find() mechanism? See timelyportfolio@79804a5. Looks like the attached model will need to be a Promise since render is async.

Here is a quick example.

library(htmlwidgets)
library(anyhtmlwidget)

esm <- "
function render({ el, model }) {
  el.style.border = '4px solid red';
  let count = () => model.get('count');
  let btn = document.createElement('button');
  btn.innerHTML = `count is ${count()}`;
  btn.addEventListener('click', () => {
    model.set('count', count() + 1);
    model.save_changes();
  });
  model.on('change:count', () => {
    btn.innerHTML = `count is ${count()}`;
  });
  el.appendChild(btn);
}
export default { render };
"

widget <- AnyHtmlWidget$new(
  .esm = esm,
  .mode = "static",
  .height='400px',
  count = 1
)

onRender

htmlwidgets::onRender(
  widget$render(),
  htmlwidgets::JS("
async function() {
  const model = await this.model;
  model.on('change:count', function(evt) {console.log(evt.detail)})
}
  ")
)

image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions