【问题标题】:Backbone generates error when I use templates当我使用模板时,Backbone 生成错误
【发布时间】:2014-12-06 21:11:49
【问题描述】:

我是骨干网的新手 我目前正在学习模板,但是我有这个输出错误 未捕获的类型错误:无法读取未定义的 underscore.js:1305 的属性“替换” _.template underscore.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 元素进行操作。
  • 非常感谢:)
  • @jamesemanon 您能否以答案的形式提供,以便可以接受?否则这个问题将在 SO' 未回答的问题队列中永远消失:-)
  • 好的,我现在就去。谢谢

标签: javascript backbone.js


【解决方案1】:

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

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

OR - They both accomplish the same thing.


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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-20
    • 2016-12-13
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    • 2018-04-22
    相关资源
    最近更新 更多