What is the correct pattern to expose component api

9 views
Skip to first unread message

Artur Nowakowski

unread,
Oct 21, 2016, 9:17:46 AM10/21/16
to Angular
I'd like to ask you, what is the best practice to write component which expose its api outside. The use case is to implement observer pattern for component, so it should be possible to register observer as soon as possible.

I mean something like that (of course, it doesn't work, because of "TypeError: Cannot read property 'registerObserver' of undefined"): 

JS:
app.component('exampleComponent', {
bindings: {
api: '='
},
template: '<h2>component template</h2>',
controller: function ($timeout) {
var that = this;
that.observers = [];

var api = {
registerObserver: function (observer) {
that.observers.push(observer);
},
someMethod1: function () {
alert('It works!');
},
someMethod2: function () {
alert('It works too!');
}
};

that.api = api;

$timeout(function asyncJob() {
var jobResult = 'job result',
observer;
for (observer in that.observers) {
observer.onNotify(jobResult);
}
}, 3000);
}
});

app.controller('MyCtrl', function ($scope) {
function Observer() {
this.onNotify = function (jobResult) {
alert(jobResult);
};
}

$scope.exampleComponentAPI.registerObserver(new Observer());
});


HTML

<div ng-controller="MyCtrl">
<example-component api="exampleComponentAPI"></example-component>
</div>


I think my solution will be passing  'Observable' object instance (with list of observers and register method) initialized in controller, into component, but I'd like to ask you for suggestions for a better solution.



Reply all
Reply to author
Forward
0 new messages