2016-11-10 47 views
1

下面的代碼演示zone.js功能:無法從<a href="https://github.com/angular/zone.js/" rel="nofollow noreferrer">here</a>瞭解zone.js例如

Zone.current.fork({}).run(function() { 
    Zone.current.inTheZone = true; 

    setTimeout(function() { 
     console.log('in the zone: ' + !!Zone.current.inTheZone); 
    }, 0); 
}); 

console.log('in the zone: ' + !!Zone.current.inTheZone); 

上面將記錄:

'in the zone: false' 

'in the zone: true' 

我真的不明白它是什麼該區域正在這裏做,它與截獲this video談到的事件有什麼關係。

它輸出false第一次因爲Zone.current.inTheZoneundefined,因爲我們改變Zone.current.inTheZone = true;,現在是被ouputted第二時間的價值。有什麼特別的是zone在這裏做?

+0

它可以幫助你瞭解http://blog.thoughtram.io/angular/2016/01/22/understanding-zones.html –

回答

0

區域允許您持續封裝在區域內的異步操作的一些屬性。所以基本上在這裏表明,沒有inTheZone屬性附加到當前區域。但是當執行zone.fork().run()時,回調將在新的分叉區域中執行,異步任務setTimeout也將在此分叉區域中執行。你會得到這個區域內的inTheZone屬性,但它不能在其他區域訪問。這可能是一個更好的例子:

Zone.current.fork({}).run(function() { 
    Zone.current.inTheZone = true; 

    setTimeout(function() { 
     console.log('in the zone: ' + !!Zone.current.inTheZone); // true 
    }, 2000); 
}); 

setTimeout(function() { 
    console.log('in the zone: ' + !!Zone.current.inTheZone); // false 
}, 1000); 

正如你所看到的,這裏有兩個異步任務。並且來自當前區域的setTimeout將比分叉區域的超時更早執行。 run()是同步的,因此inTheZone應在第一個setTimetout執行之前設置爲true。但它被記錄爲false,因爲當前區域無法從分叉區域訪問屬性。

相關問題