kristian nissen
kristian nissen

Reputation: 2907

How to add Rx.Observable.fromEvent to ajax content

I have some content that I'm fetching using Ajax, it's a json object. That object is displayed in the browser

var stateSubjectSub = stateSubject.subscribe(function(data) {
console.log('state changes');
console.log(data);

var list = document.querySelector('#state .mdl-list');
if (list) {
    document.getElementById('state').removeChild(list);
}

if (data.objectives && data.objectives.length > 0) {
    document.getElementById('state').appendChild(h('ul.mdl-list',
        data.objectives.map(function(item) {
            return h('li.mdl-list__item.mdl-list__item-three-line', {
                    'data-type': 'objective'
                },
                h('span.mdl-list__item-primary-content',
                    h('span',item.title)
                ),
                h('span.mdl-list__item-text-body', 'some stuff goes here'),
                h('span.mdl-list__item-secondary-content',
                    h('a.mdl-list__item-secondary-action', {
                        href: '#'
                    }, h('i.material-icons.mdl-badge.mdl-badge--overlap', {
                        'data-badge': item.initiatives ? item.initiatives.length : 0
                    }, 'assistant_photo'))
                )
            );
        })
    ));
}
state = data;

}, function(err) {
    console.log(err);
});

The Ajax is loaded, state is updated and the DOM is build. Everything is working as expected. My question is, how do I add subscribers to something that does not exist at the document.ready? I need to tie an observer to something that appears in the future. How can I do that using RxJS? Specifically I want to add the observable to the ul -> li -> a element

I'm not using jQuery or anything like that and I'd like to stick with just RxJS

Upvotes: 2

Views: 389

Answers (1)

demarchisd
demarchisd

Reputation: 732

You could create an Observable using the Observable.fromEvent:

/** Build DOM elements like ul -> li -> a **/

var anchor = //the anchor element that you're creating dynamically

var source = Rx.Observable.fromEvent(anchor, 'click');

var subscription = source.subscribe(
    function (x) {
        console.log('Next: Clicked!');
    },
    function (err) {
        console.log('Error: ' + err);
    },
    function () {
        console.log('Completed');
    });

Upvotes: 1

Related Questions