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
296 views
in Technique[技术] by (71.8m points)

javascript - uncaught TypeError: Cannot call method 'replace' of undefined backbone.js

I 'm trying to develop a simple RSS app using backbone.js. I 'm using this backbone.js tutorial. I 'm getting the following error, on line 2(template), when defining the template. Can someone also tell me why is tagName: "li" defined in the tutorial?

uncaught TypeError: Cannot call method 'replace' of undefined backbone.js

Javscript

window.SourceListView = Backbone.View.extend({
    tagName:"li",
    template: _.template($('#tmpl_sourcelist').html()),

    initialize:function () {
        this.model.bind("change", this.render, this);
        this.model.bind("destroy", this.close, this);
    },

    render:function (eventName) {
        $(this.$el).html(this.template(this.model.toJSON()));
        return this;
    },

    close:function () {
        $(this.el).unbind();
        $(this.el).remove();
    }
});

HTML

 <script type="text/template" id="tmpl_sourcelist">
                        <div id="source">
                        <a href='#Source/<%=id%>'<%=name%></a>
                        </div>
                </script>

thanks

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You're getting your error right here:

template: _.template($('#tmpl_sourcelist').html()),

Part of _.template's internals involves calling String#replace on the uncompiled template text on the way to producing the compiled template function. That particular error usually means that you're effectively saying this:

_.template(undefined)

That can happen if there is no #tmpl_sourcelist in the DOM when you say $('#tmpl_sourcelist').html().

There are a few simple solutions:

  1. Adjust your <script> order so that your #tmpl_sourcelist comes before you try to load your view.
  2. Create the compiled template function in your view's initialize instead of in the view's "class" definition:

    window.SourceListView = Backbone.View.extend({
        tagName:"li",
        initialize:function () {
            this.template = _.template($('#tmpl_sourcelist').html());
            //...
    

As far as tagName goes, the fine manual has this to say:

el view.el

[...] this.el is created from the view's tagName, className, id and attributes properties, if specified. If not, el is an empty div.

So having this in your view:

tagName: 'li'

means that Backbone will automatically create a new <li> element as your view's el.


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

...