0

我刚刚开始使用 Backbone 并完成了一个教程。我跟着并输入了代码,当我到最后(整个测试我得到underscore cannot call 'replace' of null

就像我说的 - 刚刚开始,所以任何关于如何修复以及为什么它坏了的信息都会很棒!

HTML

<!-- ## CART CONTAINER ## -->
<div id="yourcart"></div>

<!-- ## SCRIPTS ## -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="js/underscore.js"></script>
<script src="js/backbone.js"></script>
<script src="js/cart.js"></script>

<!-- ## TEMPLATE ## -->
<script id="itemTemplate" type="text/template">
    <img src="<%= photo %>" alt="<%= title %>">
    <div>
        <h2><%= title %></h2>
        <h4>&pound;<%= price %></h4>
    </div>
</script>

JAVASCRIPT

//  MODEL

var Item = Backbone.Model.extend({

  defaults: {

    price: 35,
    photo: "http://www.placedog.com/100/100"

  }

});

//  COLLECTION

var Cart = Backbone.Collection.extend({

  model: Item

});

var items = [

  { title: "Macbook Air", price: 799 },
  { title: "Macbook Pro", price: 999 },
  { title: "The New iPad", price: 399 },
  { title: "Magic Mouse", price: 50 },
  { title: "Cinema Display", price: 799 }

];

var cartCollection = new Cart(items);

// ITEM VIEW

var ItemView = Backbone.View.extend({

  tagName: "div",
  className: "item-wrap",
  template: $('#itemTemplate').html(),

  render: function() {
    var templ = _.template(this.template);
    this.$el.html(templ(this.model.toJSON()));
    return this;
  }

});

// COLLECTION VIEW

var CartCollectionView = Backbone.View.extend({

  el: $('#yourcart'),
  initialize: function() {
    this.collection = cartCollection;
    this.render();
  },
  render: function() {
    this.collection.each(function(item) {
        this.renderItem(item);
    }, this);
  },
  renderItem: function(item) {
    var itemView = new ItemView({ model: item });
    this.$el.append(itemView.render().el);
  }

});

$(function() {  
  var cart = new CartCollectionView();
});
4

1 回答 1

1

没有看到有关HTML/位置的任何信息Scripts,但是一旦我将template代码移到其余脚本之上,它就可以完美运行。

于 2012-10-20T14:49:21.257 回答