Uncaught TypeError: Cannot call the "replace" method from undefined underscore.js

I am new to backbone.js and underscore.js .

HTML:

 <div id="cartlist"> <script type="text/template" id="cart_template"> </script> </div> 

Where I named the view file:

 <script type="text/javascript" src="webcore/views/CartView.js"></script> </body> 

JS function (works well with javascript project):

  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; } 

This Views:

 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()) }); 
  • when I try to call a presentation template, I get an error Uncaught TypeError: Cannot call method 'replace' of undefined - underscore.js . Please help me find a mistake.

  • How to convert str string to Cart class in template from underscore.js .

Any help would be greatly appreciated, thanks.

+4
source share
1 answer

I would suggest that your problem is that you are storing #cart_template in the DOM:

 <div id="cartlist"> <script type="text/template" id="cart_template"> </script> </div> 

You create your CartList as follows:

 var cart_view = new CartList({ el: $("#cartlist").html(myCart.showCart()) }); 

When you say this:

 $("#cartlist").html(myCart.showCart()) 

everything that was inside #cartlist , in particular #cart_template . Then inside CartList you try to do this:

 _.template( $("#cart_template").html(), {} ); 

But at this point there is more #cart_template , so $('#cart_template').html() is undefined and that where your error occurs: _.template will call replace internally, but you give it undefined as instead of a string.

The solution is to move your #cart_template outside of the #cartlist .

I would also recommend that you do not pass el the view constructor, your view should create its own el , and the caller should put that el where it wants it in the DOM. Thus, the view is fully responsible for its element, and you will have less problems with zombies and events.

+10
source

All Articles