Trouble with Backbone and Typescript

2019-09-20 00:59发布

I am learning backbone over Typescript and I got the header file for backbone. I am trying to create a view in which I've referenced "this" inside the render function. But Webstorm is throwing an error on that:

class QuestionView extends Backbone.View{
    model = new Question();
    template: (data:any) => string;

    constructor(options){
        super(options);
        this.tagName = "div";
        this.template = _.template($("#add-question").html());
        _.bindAll(this, "render");
    }

    render(){
        this.$el.html()(this.template(this.model.toJSON())); // The error is pointing to   the first "this" literal in this line
        return this;
    }
}

Error:

C:/.../Main.ts(40,9): error TS2088: Cannot invoke an expression whose type lacks a call signature.

1条回答
小情绪 Triste *
2楼-- · 2019-09-20 02:06

Usually with this problems it is related to scope, but in your case it is just related to a typo in your html method call:

render(){
    this.$el.html(this.template(this.model.toJSON())); // fixed
    return this;
}

To set the HTML of an element, you pass the HTML inside the parenthesis of the html method - you accidentally passed no arguments (so this GETS the HTML, rather than SETS the HTML) and then tried to call the resulting string of HTML like a function.

this.$el.html() // returns a string of HTML
this.$el.html('<div>Hello World</div>') // sets the html to the supplied string
查看更多
登录 后发表回答