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.
--
You received this message because you are subscribed to the Google Groups
"Angular" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.