2017-07-28 150 views
2

我剛開始用Aurelia框架學習Typescript。我已經在Aurelia的Todo應用中實現了Matthew Davis的博客TypeScript Enums中的Aurelia模板使用ViewEngineHooks http://davismj.me/blog/template-constants/打字稿枚舉默認值

我希望將默認枚舉值設置爲列表中的第二個值,並將默認值設置爲列表中的第一個值。

另外我想請想知道,如果{藤,優先級}或{只是}的Todo需要進口,如待辦事項,list.ts顯示

todo.ts

// Pro Tip: By starting our enum at 1, we ensure that all values in the enum are truthy. 
export enum Priority { 
    High = 1, 
    Medium, 
    Low 
} 

export class Todo { 
    @observable done; 
    //*** Setting priority: Priority = 2 OR priority: Priority = Priority.Medium - Does not change the default from High/1 *** 
    //constructor(public list: TodoList, public description: string, public priority: Priority = 2, public editing: boolean = false) { 
    constructor(public list: TodoList, public description: string, public priority: Priority = Priority.Medium, public editing: boolean = false) { 
     this.list = list; 
     this.description = description; 
     //*** Setting this.priority = 2 OR this.priority = Priority.Medium - Does not change the default from High/1 ; 
     //this.priority = 2; 
     this.priority = Priority.Medium; 
     this.editing = false; 
    } 

待辦事項列表.TS

//*** Is {Todo} OR {Todo, Priority} needed for importing? *** 
//import {Todo} from './todo'; 
import {Todo, Priority} from './todo'; 
... 
    add(description) { 
    if (description) { 
     //*** Setting (this, description, 2) OR (this, description, Priority.Medium) - Does not change the default from High/1 *** 
     //this.todos.push(new Todo(this, description, 2)); 
     this.todos.push(new Todo(this, description, Priority.Medium)); 
     this.invalidateView(); 
    } 
    } 

todo.html

<select id="priority" value.bind="type"> 
    <option value.bind="Priority[type]" repeat.for="type of Prioritys">${type}</option> 
</select> 
+0

在我的博客中有一個錯字,感謝您幫我找到它 –

回答

0

據我所知當聲明一個變量時,你不能設置一個枚舉的默認值,與數字或布爾值相同的方式沒有默認值。 但是,您可以像構造函數(priority: Priority = Priority.Medium)中那樣爲函數參數定義默認值,以便在調用構造函數時不必提供該參數。

兩個附加說明: 是不是應該是this.priority = priority; this.editing = editing;而不是this.priority = Priority.Medium; this.editing = false;?其次,如果您將public放在參數前面,則會自動添加並分配類屬性,因此您不需要構造函數的附加行。但是對於更復雜的類,我可能會手動創建和分配屬性。

關於第二個問題:只要引用該枚舉,就需要導入Priority,例如在編寫Priority.Medium時。當您比較例如Priority類型的兩個不同屬性而不使用枚舉的名稱(例如this.todos[0].priority === this.todos[1].priority)時,不必導入它。

1

<option>小號

之所以沒有使用model.bind正在改變這是因爲正確的價值還沒有被「分配」到<option>。爲此,您需要使用model屬性。

<select id="priority" value.bind="type"> 
    <option model.bind="Priority[type]" repeat.for="type of Priorities"> 
    ${type} 
    </option> 
</select>