我是 backbone.js
和 underscore.js
的新手。
HTML:
<div id="cartlist">
<script type="text/template" id="cart_template">
</script>
</div>
我调用 View 文件的地方:
<script type="text/javascript" src="webcore/views/CartView.js"></script>
</body>
JS函数(与javascript项目配合良好):
function Cart(){
......
this.showCart = function (){
var item = deserializeJSONToObj(window.localStorage.getItem(Cart.storageName));
var str = '<table id="showcart">';
str += '<tr><td class="cartitemhead">Item to buy</td><td class="cartitemhead" style="text-align: center;">Quantity</td></tr>';
$.each(item, function(i, item) {
str += '<tr><td><table class="verticallist"><tr><td rowspan="4" style="width: 120px;"><img src="' + item.PictureName + '" alt="Product" width="95px"/></td><td style="font-weight: bold;">'+trimString(item.Name,50)+'</td></tr><tr><td><i>Available in Stock(s)!</i></td></tr><tr><td><i>Rating: 650Va-390w Input: Single</i></td></tr></table></td><td class="centertxt">'+item.QuantityInCart+'</td></tr>';
});
str += '</table>';
return str;
}
这是 View :
var myCart = new Cart();
CartList = Backbone.View.extend({
initialize:function(){
this.render();
},
render: function(){
var template = _.template( $("#cart_template").html(), {} );
this.$el.html( template );
}
});
var cart_view = new CartList({ el: $("#cartlist").html(myCart.showCart()) });
当我尝试调用 View 模板时,出现错误
Uncaught TypeError: Cannot call method 'replace' of undefined - underscore.js
。请帮我找出错误。如何将
Cart
类中的str
字符串转换为underscore.js
的template
.
非常感谢任何帮助,谢谢。
最佳答案
我猜你的问题是你在 DOM 中存储 #cart_template
的地方:
<div id="cartlist">
<script type="text/template" id="cart_template">
</script>
</div>
您可以像这样创建您的 CartList
:
var cart_view = new CartList({ el: $("#cartlist").html(myCart.showCart()) });
当你这样说时:
$("#cartlist").html(myCart.showCart())
#cartlist
中的所有内容都消失了,特别是 #cart_template
消失了。然后在 CartList
中,您尝试这样做:
_.template( $("#cart_template").html(), {} );
但是那时没有更多的 #cart_template
所以 $('#cart_template').html()
是 undefined
那是你的错误来自哪里:_.template
将在内部调用 replace
但你给它 undefined
作为模板而不是字符串。
解决方案是将您的 #cart_template
移到 #cartlist
之外。
我还建议您不要将 el
传递给 View 的构造函数,您的 View 应该创建自己的 el
并且调用者应该将 el
在 DOM 中它想要的位置。这样, View 将完全负责其元素,并且您将遇到更少的僵尸和事件问题。
关于javascript - 未捕获的类型错误 : Cannot call method 'replace' of undefined underscore. js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18994799/