2017-10-10 34 views
0

我有一個變量訂閱的遞歸問題。aurelia變量觀察者繼續遞歸調用自己

@bindable year; 

yearChanged(newVal, oldVal) { 
    if (newVal) { 
    this.year = this.year + '2017'; //just an example 
    } 
} 

因此,你可以看到即時通訊使用Aurelia對話來監聽變量的變化。當用戶改變該變量的值時,我想在其末尾添加'2017'。

但是,當我改變年的價值,它會導致對同一功能的遞歸調用。它一直調用相同的函數,直到應用程序崩潰。

Aurelia有沒有辦法阻止它這樣做?謝謝

回答

1

yearChanged只要year屬性發生更改就會被調用。您正在更改yearChanged回調中的year屬性,因此您創建了一個無限循環。您應該注意,當調用yearChanged時,已經設置了year屬性(這是回調爲yearChanged而不是yearIsAboutToChange)。

我認爲會有很多方法來解決這個問題。最簡單的可能是在你的視圖模型上創建一個附加屬性。一個屬性是可綁定的,可用於更改檢測,另一個屬性可用於顯示目的。

@bindable year; 
displayYear; 

yearChanged(newVal, oldVal) { 
    if (newVal) { 
    this.displayYear = this.year + '2017'; //just an example 
    } 
} 

你也可以短路循環:

@bindable year; 

yearChanged(newVal, oldVal) { 
    if (newVal && oldVal + '2017' !== newVal) { 
    this.year = this.year + '2017'; //just an example 
    } 
} 

再次,沒有更多的情況下是很難說,但是從你提供的代碼,它很可能是一個Value Converter是你真正想要的是什麼。

0

如果它只是爲了表示的目的,我會去與價值轉換器。 仍然有合法的情況下,當你需要這樣做(包裝第三方組件)。然後,你可以做到以下幾點:

import {TaskQueue} from 'aurelia-task-queue'; 
import {inject} from 'aurelia-dependency-injection'; 

@inject(TaskQueue) 
class MyCustomElement { 
    constructor(queue) { 
    this.queue = queue; 
    } 

    setPropertyOfInterestInternally(value) { 
    this.internalSet = true; 
    // setting the property here will make the 
    // the underlying mechanics to enqueue a task 
    // on the micro task queue - to invoke the change handler 
    // it will not be invoked in the current call stack 
    this.propertyOfInterest = value; 
    // we schedule another task on the micro task queue 
    // the arrow function(task) will run after the change handler 
    this.queue.queueMicroTask(() => this.internalSet = false); 
    } 

    propertyOfInterestChanged() { 
    // if the set is internal => skip 
    if (this.internalSet) { return; } 
    // ... 
    } 
} 

的任務執行同步 - 他們等待完成的異步工作。