【问题标题】:UnderscoreJS Uncaught TypeError: Cannot call method 'replace' of undefinedUnderscoreJS Uncaught TypeError:无法调用未定义的方法“替换”
【发布时间】:2013-03-27 01:37:50
【问题描述】:

在我的 Backbone 视图中,我有:

noteTemplate: _.template($('#note-template').html()),

这是引发此错误的原因。模板是:

<script type="text/template" id="note-template">
    <div class="reminder">
        <div class="reminder-hover">
            <div class="title"><%= title %></div>
            <div class="created">Created 3 days ago <span class="pull-right"> In 3 hours</span></div>
        </div>
        <span class="id" style="display: none;"><%= id %></span>
    </div>
</script>

我很困惑,因为这在我的控制台中有效:

&gt;&gt; _.template($('#note-template').html());
function (n){return e.call(this,n,w)}

完整代码如下:

App.Views.Index = Backbone.View.extend({

    el: $("div.reminders"),
    todays : $("span.today"),
    tomorrows : $("span.tomorrow"),
    weeks : $("span.week"),
    all_times : $("span.all-time"),

    noteTemplate: _.template($('#note-template').html()),


    events: {
        "click .reminder" : "editNote",
        "click .newNote"  : "newNote"
    },

    initialize : function() { 
        _.bindAll(this, 'render');
        this.notes = this.options.notes;
        this.listenTo(this.model, 'change', this.render);
    },

    render : function() {
        // Hide things related to editing a note 
        this.$("[name=content]").hide().val("");
        this.$("[name=title]").hide().val("");
        this.$("save1").hide();
        this.$("close1").hide();

        // Fill in content
        this.$el.html( this.noteTemplate( this.model.toJSON() ) );
        this.$todays.html( collection.getTodays.length );
        this.$tomorrows.html( collection.getTomorrows.length );
        this.$weeks.html( collection.getWeeks.length );
        this.$all_times.html( collection.getAllTimes.length );
        return this;
    },

    editNote : function() {
        this.goTo("notes/"+this.model.id);
    },

    newNote : function(){
        this.goTo("newNote");
    }

});

【问题讨论】:

    标签: javascript backbone.js underscore.js


    【解决方案1】:

    不要在定义方法时尝试缓存笔记模板 HTML,而是在初始化视图时进行。

    initialize : function() { 
        // ...
        this.nodeTemplate = _.template($('#note-template').html());
    }
    

    您很可能在加载 DOM(以及模板)之前定义视图。

    【讨论】:

      【解决方案2】:

      另一种解决方案是移动调用视图上方的标记脚本,像这样(我正在使用jade)

      script#page-thumb(type='text/template')
          .page-thumb-container.relative
            .page-thumb
              .image
                figure
                  img(src='{{ image }}' , width='80px',height='60px' , data-id='{{ id }}')
                span.title {{ title }}
            .page-dragger.absolute
      
      script(src='js/src/views/PageThumbView.js')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-09-06
        • 2014-09-18
        • 2012-06-12
        • 1970-01-01
        • 1970-01-01
        • 2015-04-04
        • 1970-01-01
        相关资源
        最近更新 更多