custom element, custom event handler attributes - custom-element

Built in browser elements have event attributes which execute arbitrary javascript as described below
Is there any way to create a custom element with a similar behaving custom event handler attribute, and is there a standard pattern for doing so? Where the {some custom eventType}="{some code}" executes with the correct values in scope and the this binding set correctly.
<some-custom-element oncustomevent="alert('worked')" />

First question is: Do you really want to allow executing code from a string? Because it requires eval()
There is nothing wrong with using eval() when you understand the implications:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode
Trigger dynamic (string) code:
from a Custom Element attribute onevent
from a Custom Element setter onevent
from a Custom Event onevent detail (see connectedCallback)
function triggerEvent(name, code = "console.warn('No code parameter')") {
console.log(name, this);
if (this === window) console.warn('no element scope');
try {
if (typeof code === "string") eval(code);
else console.warn("code is not a string")
} catch (e) { console.error(e) }
}
customElements.define("my-element", class extends HTMLElement {
static get observedAttributes() {
return ['onevent'];
}
constructor() {
super();
this.onclick = () => triggerEvent.call(this, "element Click", "console.log('from element click')");
}
connectedCallback() {
document.addEventListener("onevent", evt => {
triggerEvent.call(this, "EventListener", evt.detail);
})
}
attributeChangedCallback(name, oldValue, newValue) {
if (name === "onevent") {
triggerEvent.call(this, "attributeChangedCallback", newValue);
}
}
set onevent(newValue) {
triggerEvent.call(this, "setter", newValue);
}
});
setTimeout(() => document.dispatchEvent(new CustomEvent("onevent", {
detail: "console.log('from dispatchEvent detail')"
})), 2000); //execute after elements listen
<my-element onevent="console.log('from element attribute')">click my-element</my-element>
<button onclick="document.querySelector('my-element').onevent='console.log("from button")'"
>Call setter</button>
JSFiddle playground at: https://jsfiddle.net/WebComponents/ezacw5xL/

Related

Aurelia: EventAggregator fires twice

The function called by the subscription function triggers twice.
The publisher is not being used in an activate or attached function, but in an async function of a different class. Both classes recieve the same EventAggregator through binding.
Console.Trace() has the same routes in both cases. The Publish/Subscribe set is unique and not used by any other classes.
async sender(item:any):Promise<void> {
this.dialogService.open({
viewModel: CaModalConfirm,
model: {
color: this.color
}
}).whenClosed(async response => {
if (response.wasCancelled === false) {
this.moduleName = params.params.moduleId;
await this.selectionEventAggregator.publish('requestSelection',{item: item});
this.elementEventAggregator.publish('hideSidebar');
}
});
}
---------------------------------------------
attached() {
this.subscriptions.push(
this.selectionEventAggregator.subscribe(
'requestSelection',
params => this.sendSelection(params)
)
);
}
sendSelection(params):void {
console.trace(params);
this.selectionEventAggregator.publish(
'sendSelected',
{
selection: this.itemSelection,
item: params.item
}
);
}
The Custom Element which contained the custom Element with the Subscription has been used twice, which caused the issue. This was not an EventAggregator issue.

VueJS: Adding a class to one element if a class exists on another element

I'm working in VueJS. I'm trying to bind a class to one element based on an existence of a class on another element. The below is in a :for loop to print out the list.
The '#accordion-'+(index+1)) is the id of the div I want to check to see if a class exists on it.
I wrote a method and it works UNTIL I check the element's classList. Right now, I'm only doing a console log, but eventually this will return true and hopefully the class will apply.
methods: {
existingTopic: function(lcDivID) {
const element = document.querySelector(lcDivID);
console.log(element); //It gives me the element.
/* The below is where it crashes */
console.log(element.classList.contains("collapsePanelExistingTopic"));
}
}
I find it so frustrating. I've spent a day on this without any results. Any help you can provide it would be great.
Here it is, you can also use this.$el as document
...
methods: {
hasClass() {
const element = this.$el.querySelector('h1')
if (element.classList.contains('your-class-here')) {
console.log(true)
this.$el.querySelector('anotherelement').classList.add("your-another-class");
} else {
console.log(false)
}
}
},
mounted() {
this.hasClass()
}
...
Alternative
<h1 class="mb-5 fs-lg" ref="myElement">Sign up</h1>
...
methods: {
hasClass() {
const element = this.$refs.myElement
if (element.classList.contains('mb-5')) {
console.log(true)
this.$el.querySelector('anotherelement').classList.add("your-another-class");
} else {
console.log(false)
}
}
},
mounted() {
this.hasClass()
}
...
So you can define ref as :ref="index+1" in your loop

Aurelia `click` attribute that requires event target to be same as element

I'm aware of click.trigger as well as click.delegate which work fine. But what if I want to assign a click event that should only trigger when the exact element that has the attribute gets clicked?
I'd probably do something like this were it "normal" JS:
el.addEventListener('click', function (e) {
if (e.target === el) {
// continue...
}
else {
// el wasn't clicked directly
}
});
Is there already such an attribute, or do I need to create one myself? And if so, I'd like it to be similar to the others, something like click.target="someMethod()". How can I accomplish this?
Edit: I've tried this which doesn't work because the callback function's this points to the custom attribute class - not the element using the attribute's class;
import { inject } from 'aurelia-framework';
#inject(Element)
export class ClickTargetCustomAttribute {
constructor (element) {
this.element = element;
this.handleClick = e => {
console.log('Handling click...');
if (e.target === this.element && typeof this.value === 'function') {
console.log('Target and el are same and value is function :D');
this.value(e);
}
else {
console.log('Target and el are NOT same :/');
}
};
}
attached () {
this.element.addEventListener('click', this.handleClick);
}
detached () {
this.element.removeEventListener('click', this.handleClick);
}
}
And I'm using it like this:
<div click-target.bind="toggleOpen">
....other stuff...
</div>
(Inside this template's viewModel the toggleOpen() method's this is ClickTargetCustomAttribute when invoked from the custom attribute...)
I'd also prefer if click-target.bind="functionName" could instead be click.target="functionName()" just like the native ones are.
Just use smth like click.delegate="toggleOpen($event)".
$event is triggered event, so you can handle it in toggleOpen
toggleOpen(event) {
// check event.target here
}
Also you can pass any other value available in template context to toggleOpen.

Binding the Dialog to my angular controller

I am trying to bind a MetroUI modal dialog to an angular controller property. This way I can show and hide the dialog using binding.
DIRECTIVE
appMod.directive('showDialog', ['$timeout', function ($timeout): ng.IDirective {
return {
restrict: 'A',
link: function (scope, element, attrs, ngModel) {
scope.$watch(attrs.showDialog, function (value) {
if (value) {
element.show();
}
else {
element.hide();
}
});
}
}
}]);
HTML:
<div class="padding20 dialog" id="dialog9"
data-role="dialog" data-close-button="true"
data-overlay="true" data-overlay-color="op-dark"
show-dialog="vm.isDialogVisible">
This way I can control opening the dialog by setting the vm.isDialogVisible Boolean on my controller.
Problem is that I am trying to update the vm.isDialogVisible attribute when the user closes the dialog (via the close button). Anyone has some ideas how to fix that?
It is always cool to find your own solution (took me a day :-)). I made a mistake to use the show / hide features of the element. I should have used the data attribute of the element. That way I am able to access the
onDialogClose
function, which enable me to update the scope. Below my solution
appMod.directive(showDialog, ['$timeout','$parse',function ($timeout, $parse){
return {
restrict: 'A',
scope:false,
link: function (scope, element, attrs) {
var e1 = theDialog.data('dialog');
$timeout(() => {
e1.options.onDialogClose = (dialog) => {
var model = $parse(attrs.showDialog);
model.assign(scope, false);
scope.$digest();
};
}, 0);
scope.$watch(attrs.showDialog, function (value) {
if (value) {
e1.open();
}
else {
e1.close();
}
});
}
}
}]);

Durandal Custom View Location Strategy

I am trying to figure out how to use a custom view location strategy, I have read the documentation at this page http://durandaljs.com/documentation/Using-Composition/ but I don't exactly understand what the strategy function should look like.
Can anybody give me a quick example of what the implementation of this function would be like and the promise that returns (even a simple one) etc?
Thanks in advance,
Gary
p.s. This is the code in my html:
<div>
<div data-bind="compose: {model: 'viewmodels/childRouter/first/simpleModel', strategy:
'viewmodels/childRouter/first/myCustomViewStrategy'}"></div> </div>
and this is the code in my myCustomViewStrategy:
define(function () {
var myCustomViewStrategy = function () {
var deferred = $.Deferred();
deferred.done(function () { console.log('done'); return 'simpleModelView'; });
deferred.fail(function () { console.log('error'); });
setTimeout(function () { deferred.resolve('done'); }, 5000);
return deferred.promise();
};
return myCustomViewStrategy;
});
but I get the error:
Uncaught TypeError: Cannot read property 'display' of undefined - this is after done has been logged in the console window.
Okay I solved this by creating my custom view strategy by the following:
define(['durandal/system', 'durandal/viewEngine'], function (system, viewEngine) {
var myCustomViewStrategy = function () {
return viewEngine.createView('views/childRouter/first/sModelView');
}
return myCustomViewStrategy;
});
As I found the documentation a bit lacking on compose binding's strategy setting I checked the source code how it works. To summ it up:
The module specified by the compose binding's strategy setting by its moduleId
must return a function named 'strategy'
which returns a promise which results in the view to be bound
as a HTML element object.
As a parameter the strategy method receives the compose binding's settings object
with the model object already resolved.
A working example:
define(['durandal/system', 'durandal/viewEngine'], function (system, viewEngine) {
var strategy = function(settings){
var viewid = null;
if(settings.model){
// replaces model's module id's last segment ('/viewmodel') with '/view'
viewid = settings.model.__moduleId__.replace(/\/[^\/]*$/, '/view');
}
return viewEngine.createView(viewid);
};
return strategy;
});
Durandal's source:
// composition.js:485
for (var attrName in settings) {
if (ko.utils.arrayIndexOf(bindableSettings, attrName) != -1) {
/*
* strategy is unwrapped
*/
settings[attrName] = ko.utils.unwrapObservable(settings[attrName]);
} else {
settings[attrName] = settings[attrName];
}
}
// composition.js:523
if (system.isString(context.strategy)) {
/*
* strategy is loaded
*/
system.acquire(context.strategy).then(function (strategy) {
context.strategy = strategy;
composition.executeStrategy(context);
}).fail(function(err){
system.error('Failed to load view strategy (' + context.strategy + '). Details: ' + err.message);
});
} else {
this.executeStrategy(context);
}
// composition.js:501
executeStrategy: function (context) {
/*
* strategy is executed
* expected to be a promise
* which returns the view to be bound and inserted to the DOM
*/
context.strategy(context).then(function (child) {
composition.bindAndShow(child, context);
});
}