简体   繁体   中英

Uncaught TypeError: Object [object Object] has no method 'replace' with backbone.js and coffeescript

Person = Backbone.Model.extend(
  defaults: 
    name: 'Jony James'
    age: 30
    occupation:  'developer'

  validate: (attrs) ->
    if attrs.age < 0
      return 'Age must be positive, stupid.'
    if not attrs.name
      return 'A person must have a name! fool.'

  work: ->
    @get('name') + " is working." 
    )

PersonView = Backbone.View.extend({
    tagName: 'li'

    #template: _.template($('#personTemplate').html())
    template: "#personTemplate"

    initialize: ->
      @render()

    render: ->
      template = _.template($(@template))
      @$el.html(template)

    })

person = new Person
personView = new PersonView( model: person)
$(document.body).append personView.el

On my index.html

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title></title>
 </head>
 <body>
  <script id="personTemplate" type="text/template">
   <strong><%= name %></strong> (<%= age %>) - <%= occupation %> 
  </script>
  <script src="js/underscore.js"></script>
  <script src="js/jquery.js"></script>
  <script src="js/backbone.js"></script>
  <script src="js/main.js"></script>
 </body>
</html>

With template: _.template($('#personTemplate').html()) and @$el.html(@template(@model.toJSON())) is working fine.

but with current version of main.js I get this error in google chrome console:

Uncaught TypeError: Object [object Object] has no method 'replace'

Where is the error?

Thank you!

The error is in the template function. Try passing the html instead of a jQuery object:

template = _.template($(@template).html(), @model.toJSON())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM