LoginSignup
1
1

More than 5 years have passed since last update.

backbone.viewがtypescriptでコンパイルできない時

Last updated at Posted at 2015-02-23

typescriptになれた頃、tscさんがこんなエラーをはくようになりました。
今まで普通にbuildできていたコードが修正をいれた途端突然エラーになったので混乱しました。

A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties.

クラスのなかでプロパティに値をいれている場合は、superより前にプロパティをイジイジするの禁止らしいです。

<追記>
よくよくエラーをよめば発生する原因が書いてありました。値入りのプロパティをもっているクラス限定の話でした。
エラーは最後まで読まないとだめですね・・・

Backbone.Viewはこの書き方をよくしていたので全般的にbuildが通らなくなりました。
tsのサイトのサンプルを確認してみると

// The DOM element for a todo item...
class TodoView extends Backbone.View {

  

    constructor (options? ) {
        //... is a list tag.
        this.tagName = "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"
        };

        super(options);
   
    }

参照)
https://github.com/Microsoft/TypeScriptSamples/blob/master/todomvc/js/todos.ts

解決1

下記のように値を設定したプロパティの定義があるはずなので、
それをコンストラクタの内で値をいれるようにすればbuildが通るようになります。

class myA extend Backbone.View<Backbbone.Model>{
   this.num = 100;

}

解決2

view生成に必要なthis.tagNameとかthis.elはコンストラクタの引数として渡せばOKでした。

// The DOM element for a todo item...
class TodoView extends Backbone.View {

  

    constructor (options? ) {
        super(_.extend(options,
         tagName:"li",
         events:{
            "click .check": "toggleDone",
            "dblclick label.todo-content": "edit",
            "click span.todo-destroy": "clear",
            "keypress .todo-input": "updateOnEnter",
            "blur .todo-input": "close"
        }
        ));
   
    }

改めてリファレンスをみるとsuperに渡すほうが公式に近い書き方に思えてきます。

var ItemView = Backbone.View.extend({
  tagName: 'li'
});

参照: http://backbonejs.org/#View-el

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1