2016-05-11 21 views
2

我正在通過「掌握TypeScript」這本書,其中作者演示了使用Backbone生成模型,集合和視圖。Backbone,TypeScript和super

我已經定義了以下類:

export class ContactItemView extends Backbone.View<cm.ContactModel> { 
    template: (properties?: any) => string; 
    constructor(options?: any) { 
     this.className = "contact-item-view"; 
     this.template = _.template(contactItemSnippet); 
     this.events = <any>{ 'click': this.onClicked }; 
     super(options); 
    } 
... 
} 

不幸的是,打字稿不會錯誤編譯如下:

Build: 'super' must be called before accessing 'this' in the constructor of a derived class

然而,如果我將調用超級上述「這個」

export class ContactItemView extends Backbone.View<cm.ContactModel> { 
    template: (properties?: any) => string; 
    constructor(options?: any) { 

     super(options); 

     this.className = "contact-item-view"; 
     this.template = _.template(contactItemSnippet); 
     this.events = <any>{ 'click': this.onClicked }; 
    } 
... 
} 

然後我的事件不會觸發。我唯一能做的就是解決這個問題,將調用改爲super,在生成的JavaScript代碼中使用「this」,從而修改TypeScript編譯的內容。

有沒有辦法讓我的事件工作,同時仍然堅持正確的TypeScript規則?

+0

值得一讀:http://benmccormick.org/2015/04/07/es6-classes-and-backbone-js/ –

+0

@RyanCavanaugh,爲感謝鏈接。這是一個很好的閱讀。由於這只是一個教程,我並不真正擔心它。我只是好奇我是否可以把它工作。看來,使用Backbone,我將無法得到這個工作。大多數;我計劃使用Angular。 –

回答

1

使用「正常」的骨幹不工作也很好,但我能得到它多一點DIY的方式完成基礎上,文章由Ryan鏈接:

export class ContactItemView extends Backbone.View<cm.ContactModel> { 
    static template: (properties?: any) => string = _.template(contactItemSnippet); 
    constructor(options?: any) { 
     super(options); 
     this.events = <any>{ 'click': this.onClicked }; 
    } 

    events(): Backbone.EventsHash { 
     return { 
      // events 
     }; 
    } 

    render(): ContactItemView { 
     this.$el 
      .addClass("contact-item-view") 
      .html(ContactItemView.template(...)); 
     return this; 
    } 
    ... 
} 
1

使用另一種可能裝飾。剛檢查出來https://github.com/dsheiko/ng-backbone/blob/master/src/core/component.ts 這@Component用於類似Angular2:

import { Component, View } from "../ng-backbone/core"; 

@Component({ 
    el: "ng-hello", 
    template: `Hello World!` 
}) 

class HelloView extends View { 
} 

let hello = new HelloView(); 
hello.render(); 

的裝飾注入指定的屬性直接進入視野的原型。因此,它們已經可用於構造函數(超級)

1

只需將「this.classname ...」和「this.events ...」移出構造函數,並將它們初始化,就像這樣(這可能不會直接滿足您的代碼,但某事類似):

initialize() { 
    //... is a list tag. 
    this.setElement($("<li />")); 
    // The DOM events specific to an item. 
    this.events = { 
     "click .check": "toggleDone", 
     "dblclick label.todo-content": "edit", 
     "click span.todo-destroy": "clear", 
     "keypress .todo-input": "updateOnEnter", 
     "blur .todo-input": "close" 
    }; 
}