Clone/Copy a Method in Javascript?

How does one clone or copy a method such that no reference to the original method is maintained?

I am trying to copy a click function on an element using the DOM and assign it to another element so I can remove the first element from the DOM without losing the function reference on the other element. I am doing this in a directive.

element.click = parent.click //need a better way to copy
element.click() //works
remove(parent)
element.click() //doesn't work

The reason why I am doing this is because I am removing the parent-wrapper tag, which has a (click) method assigned to it, so that just its inner button template remains. However, because I am removing the wrapper tag, the (click) on the parent tag is not being passed to the template button tag.

For instance, I have an app-button component with a button in its template.

Currently this is rendered:

<app-button (click) = function(1, 2)>
  <button>
  </button>
</app-button>

I want the parent tag removed, which I am doing via a DOM manipulation, but want to maintain the (click) function, like:

<button (click) = function(1, 2)>
</button>

1 answer

  • answered 2019-07-19 09:45 Taurayi

    I'm not quite sure I understand why you are trying to do what you are doing(or what it is exactly), but from my understanding, you could store a reference to the host element '' in the component class, then you can assign a listener to the <button> element in your template that triggers a click event on that reference:

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule, Component, ViewChild, ElementRef, Renderer2, OnInit} from '@angular/core';
    
    
    @Component({
      selector: 'app-root',
      template: `
        <app-button (click)="foo()"></app-button>
      `
    })
    export class AppComponent {
    
        foo() {
    
            console.log('bar');
    
        }// end function
    
    }// end class
    
    
    @Component({
      selector: 'app-button',
      template: `<button #button (click)="onClick()">Click me</button>`
    })
    export class AppButtonComponent implements OnInit {
    
        @ViewChild('button')
        private button:ElementRef;
    
        constructor(
            private element:ElementRef, 
            private renderer:Renderer2
        ) {}
    
        ngOnInit() {
    
    
            let parent = this.element.nativeElement.parentElement,
                element = this.element.nativeElement,
                button = this.button.nativeElement;
    
            this.renderer.insertBefore(parent, button, element );
            this.renderer.removeChild(parent, element);
    
        }// end function
    
        onClick() {
    
            let element = this.element.nativeElement;
    
            element.click();
    
        }// end function
    
    }// end class