Reputation: 5087
I have a section of my view (html) that is generated programmatically by a viewmodel/class. This uses the Aurelia DOM
(Aurelia Docs - pal :: Dom) functionality to generate and add the raw HTML elements to the view.
However, I am unable to get events within the generated html to call back to the viewmodel. An example:
let deleteButton = this.dom.createElement("button");
deleteButton.setAttribute("onclick", "cancelCreditNote(`${ row.creditNoteId }`)");
A click on the generated button won't call back to the viewmodel, which does have a cancelCreditNote
function. Various other things like deleteButton.setAttribute("click.delegate", "cancelCreditNote('${ row.creditNoteId }')");
do not work either.
Does anyone know how to access a viewmodel class from essentiall 'raw' html in aurelia?
Unfortunately in this instance I cannot use the standard aurelia templating to generate the HTML.
Upvotes: 2
Views: 784
Reputation: 14002
The DOM property on PAL is just an abstraction for the browser's DOM object, create element is likely just calling document.createElement
which doesn't afford any Aurelia binding to the created element.
You could try using aurelia.enhance(context, element)
which takes an existing DOM element and runs it through the templating engine.
With this method you can also pass a binding context to apply to the element.
Upvotes: 2
Reputation: 9849
In my HTML I use this:
<div id="collapsesidebar" click.delegate="toggleSidebar()">
In my view-model I have this method:
toggleSidebar(){
alert('hi');
}
You could also do this from your view-model with JQuery like this:
attached() {
$('main').on('click', ()=> alert('hi'));
}
The last option is ONLY available áfter the attached()
method is triggered: before that the binding needs to do its job and only after that the elements are located inside of the dom.
In other words: this will not work:
activate(){
$('main').on('click', ()=> alert('hi'));
}
because the constructor
and the activate
method both get fired before the attached
method.
Upvotes: 0