Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

backbone.js - Trouble with Backbone and Typescript

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.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...