问题
How would you go about accessing a DOM element in Aurelia? This is a broad and general question, but I have a feeling there are one or two preferred ways to do this. I have two current cases in Aurelia now:
In the template I have a form. I want to access the form element in the view-model, on VM canDeactivate(), to interrupt a user navigating away from a half filled out form. So the scope in which I'm trying to access the element can be considered local.
In another view-model I want to hide navigation on VM activate(). Navigation resides in another view-model/template pair so the scope may be considered global.
回答1:
As Rob suggested, use ref
. For your example:
view
<form ref="myForm"></form>
viewModel
class ViewModel {
canDeactivate() {
var form = this.myForm;
// do stuffs
}
}
For more information on the ref attribute, see here: http://aurelia.io/docs/binding/basics#function-references
回答2:
Use binding system's ref
capability. See the docs http://aurelia.io/docs/binding/basics#referencing-elements
回答3:
Another option; if your view-model is exposed as a @customElement
, its DOM element can be injected in the constructor:
@customElement
@inject(Element)
export class MyCustomElement {
constrctor(element) {
logger.info(element) // ==> <my-custom-element></my-custom-element>
}
}
回答4:
Just as another point I came across when trying to use this for myself, the ref
variable isn't available during construction, and this isn't clear in the documentation. You can begin to reference the element as mentioned above (http://aurelia.io/hub.html#/doc/article/aurelia/binding/latest/binding-basics/5) anytime during or after the attached
method is called.
回答5:
Typescript version
@transient()
@autoinject
export class ViewModel {
myForm: any;
canDeactivate() {
var form = this.myForm;
// do stuffs
}
}
来源:https://stackoverflow.com/questions/29863044/access-a-dom-element-in-aurelia