Backbone, TypeScript, and super
Backbone, TypeScript, and super
我正在阅读《掌握TypeScript》一书,作者在书中演示了使用Backbone生成模型、集合和视图。
我定义了以下类别:
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);
}
...
}
不幸的是,TypeScript不会编译这个错误:
内部版本:在派生类的构造函数中访问"this"之前,必须调用"super"
然而,如果我把电话转到"这个"之上
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 };
}
...
}
那么我的活动就不会启动。为了解决这个问题,我唯一能做的就是在使用"this"之后,将调用移动到super,在生成的JavaScript代码中移动到,从而修改TypeScript编译的内容。
有没有一种方法可以在遵守正确的TypeScript规则的同时让我的活动正常工作?
使用"普通"主干网效果不太好,但我可以根据Ryan链接的文章用更多的DIY方法完成:
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;
}
...
}
使用装饰器的另一种可能性。看看就知道了https://github.com/dsheiko/ng-backbone/blob/master/src/core/component.ts此@组件的使用类似于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();
装饰器将指定的属性直接注入到视图原型中。因此,它们已经可用于构造函数(超级)
只需将"this.classname…"answers"this.events…"从构造函数中移出,并将它们放入initialize中,如下所示(这可能不直接适合您的代码,但类似):
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"
};
}
相关文章:
- Selenium WebDriver and JavaScript change
- PHP and Javascript functions
- Javascript Return and if/else
- SetTimeout and clearTimeout in Javascript
- lightbox in html 5 and javascript
- TimelineJS and AngularJS
- timeago.js with datatable and PHP
- javascript button ajax and php
- Ajax and Json with Rails
- Combine onload, onresize and onclick
- php布尔值's小写AND大写和数字布尔值'可以接受
- setTimeout and V8
- Jquery post and onclick
- Moment js and IOS
- Rails 3.2 and Paloma gem
- Backbone, TypeScript, and super
- iframe and JavaScript on different pages
- JSON and jQuery Search
- Flash and External Javascript
- 在使用object.create创建的对象中使用super