我一直在寻找,发现很多答案,但似乎没有工作。Underscore.js模板问题 - 无法调用方法'替换'null
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
Shopping Cart
</title>
<link rel="stylesheet" href="lib/style.css" type="text/css">
</head>
<body>
<script id="rtemp" type="text/x-underscore-template"">
<span><%= title %></span>
</script>
<script src="lib/jquery.js" type="text/javascript"></script>
<script src="lib/underscore.js" type="text/javascript"></script>
<script src="lib/backbone.js" type="text/javascript"></script>
<script src="lib/script.js" type="text/javascript"></script>
</body>
<script>
var Photo = Backbone.Model.extend({
initialize: function(){
console.log('this model has been initialized');
this.bind("change:title", function(){
var title = this.get("title");
console.log("My title has been changed to.. " + title);
var pv = new PhotoView();
pv.render();
});
},
setTitle: function(newTitle){
this.set({ title: newTitle });
},
setLocation: function(newLoc)
{
this.set({location:newLoc});
}
});
var PhotoView = Backbone.View.extend
({
el: $('body'),
render: function(event)
{
var name = myPhoto.get('title');
console.info(name);
var template = _.template($('#rtemp').html(), {title:name});
console.info(this.model);
$(this.el).html(template);
return this;
}
});
</script>
</html>
首先;
创建方法
var newPhoto = new Photo();
newPhoto.setTitle('Fishing');
这项工作很好的一个新实例,它将通过模板加载到体内。但是,如果我那么做一遍,
newPhoto.setTitle('Sailing');
我得到的错误 - “无法调用空的‘取代’”
号线的错误,但我相信这是在
var template = _.template($('#rtemp').html(), {title:name});
谢谢亩太短,已经帮助了很多。我一直在用这个骨干的东西抨击我的头,但你的解释已经清除了很多问题:D – mcclennon19
优秀的解释! 1.我想知道,如果在var viewPhoto = new PhotoView({model:newPhoto})之后调用'render()';'你没有对模型进行任何修改。 2.您如何减少“渲染”次数? –
@serbanghita:很难说没有更多的细节,但你可能只是手动调用它。 –