当我使用模板时,Backbone会产生错误

Backbone generates error when I use templates

本文关键字:Backbone 错误      更新时间:2023-09-26

我是主干网的新手,我目前正在学习模板,但我有这个输出错误Uncaught TypeError:无法读取未定义下划线的属性"replace"。js:1305_.template下划线.js:1305(匿名功能)

这是我的index.js

var Person = Backbone.Model.extend({
    defaults: {
        name: 'ozan onder',
        age: 20,
        occupation: 'worker'
    }
});
var PersonView = Backbone.View.extend({
    //by default the tagname is a div element
    //but we will override it
    tagName: 'li',
    //% is how can access to a property name
    // create templer
    template: _.template($('#personTemplate').html()),
    initialize: function() {
        this.render();
    },
    render: function() {
        //set the html
        this.$el.html(this.template(this.model.toJSON()));
    }
});
var person = new Person;
var personView = new PersonView({ model: person });
console.log(personView.el);
And here is my index.html
<!DOCTYPE html>
<html> 
  <head> 
    <!--this import order is important-->
    <script src="../../library/jquery-1.8.2.min.js"></script>
    <script src="../../library/underscore.js"></script>
    <script src="../../library/backbone.js"></script>
    <script src="index.js"></script>
  </head>
  <body>
    <script id="personTemplate" type="text/template">
        <strong><%= name %></strong> (<%= age %>) - <%= occupation %>
    </script>
  </body>
</html>  

请确保将代码包装在一个jQuery就绪函数中,以便在加载页面之前不会触发它。也许您正在对代码初始化时不存在的DOM元素执行操作。

$( document ).ready(function() {
   // put your code here
});
OR - They both accomplish the same thing.

$(function() {
  // put your code here
});