Rehman Gull
Rehman Gull

Reputation: 63

How I can make a function Global in Aurelia

Here is a scenario. I want to access Aurelia function, outside the Aurelia Application. Like while running my application if I call a method "GetNotification(string Message)" through browser Console, then it should get called.

The reason is that my Aurelia Application will run in a .Net Application browser. So I want to communicate between my native application(.Net) and Aurelia application. As in .Net browser control, we can call any Javascript function. But I am unable to call Aurelia Function, as it is not exposed externally.

Upvotes: 1

Views: 144

Answers (1)

rkever
rkever

Reputation: 884

I wouldn't recommend exposing your methods directly to global namespace. What you could do would be to register a custom event handler from within your viewmodel class and then trigger it from the .net site like ...

// ViewModel within aurelia
export class MyViewModel {
    attached(){
        document.body.addEventListener('custom-event', event => {
            this.myViewModelMethod(event.detail); // just keep in mind the scope
        }, false);
    }

    myViewModelMethod(data) {
        console.log('data', data);
    }
}

// .NET (outside the aurelia app)
// keep in mind CustomEvent is supported by most browsers but for IE it's only IE11
// see: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent
document.body.dispatchEvent(new CustomEvent('custom-event', { 
    detail: {
        myData: {
           prop1:'prop1'
        }
    }
}));

Upvotes: 5

Related Questions