AngularJS中的MutationObserver知道何时加载了SPA模板

时间:2016-02-19 10:26:55

标签: angularjs mutation-observers

我在AngularJS SPA中使用MutationObserver,每次通过用户导航更新ng-view时都会检测DOM中的更改。这里有更好的解释http://www.soasta.com/blog/angularjs-real-user-monitoring-single-page-applications/

这是每次软导航(在SPA内)

时触发的功能
function initMutationObserver() {

    if (window.MutationObserver) {  

        // select the target node
        var target = document.querySelector('.sport');

        // create an observer instance
        var observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {      
                console.info(mutation.type);
            });    
            console.info('**** DOM changes ****')
        });

        // configuration of the observer:
        var config = { attributes: true, childList: true, characterData: true, subtree: true};

        // pass in the target node, as well as the observer options
        observer.observe(target, config);
    }
};

也就是说,每次用户导航到SPA中的新页面时,此观察者都会检测到DOM中的更改。

问题是,对于每个导航,这个观察者会多次被解雇,而不仅仅是一个,所以我不知道什么时候结束了。有没有人知道如何做到这一点? MutationObserver有没有办法让我确定DOM已经完成了更新,我可以调用加载?

非常感谢!

2 个答案:

答案 0 :(得分:0)

https://docs.angularjs.org/api/ngRoute/provider/ $ routeProvider

$routeProvider.when('some/path',{
  resolve: {
    data1: function(){
        //do your asynch call (promise) returning your data
    },
    data2: function(){
        //do your asynch call (promise) returning your data
    },
    controller: function(data1,data2){
      //data1 and data2 will be resolved by when controller is instantiated
    }
  }
})

或者如果你想使用ui.router

https://github.com/angular-ui/ui-router/wiki#resolve

与之前的案例非常相似

答案 1 :(得分:0)

一旦你的突变发生,你应该摧毁观察者:

observer.disconnect();

您可能已完成NodeList或其他内容......

想象一下,它是一个camera,等待所有这些DOM事件发生的时间。 (顺便说一下,你可能不需要所有这些)。

但停止活动非常重要。