TrueWheel
TrueWheel

Reputation: 987

Defining HTML template in Backbone.js using Coffeescript

I am currently converting a javascript backbone.js view into coffeescript but it isn't working correctly.

My working original Javascript view is

define([
  'jquery',
  'underscore',
  'backbone',
  'text!templates/dashboard/main.html'
], function($, _, Backbone, mainHomeTemplate){

  var Test = Backbone.View.extend({
    el: $("#page"),
    render: function(){
      this.$el.html(mainHomeTemplate);
    }
  });
  return Test;
});

My coffeescript view is

define [
  'jquery',
  'underscore',
  'backbone',
  'text!templates/dashboard/main.html'
], ($, _, Backbone, mainHomeTemplate) ->

Test = Backbone.View.extend
    el: $ '#page'

    render: ->
        $(@el).html @mainHomeTemplate

Test

When I try to initialize the test view I get it says that Test is undefined.

app_router.on('route:defaultAction', function (actions) {
      require(['views/dashboard/testnew'], function(Test) {
        console.log(Test)
        var test = new Test();
        test.render();
       });

Any help would be really appreciated. Thanks

Upvotes: 1

Views: 692

Answers (1)

mu is too short
mu is too short

Reputation: 434745

You're referencing mainHomeTemplate as an instance variable (@mainHomeTemplate, the same thing as this.mainHomeTemplate) when it just just a plain local variable. You want:

Test = Backbone.View.extend
    el: $ '#page'

    render: ->
        $(@el).html mainHomeTemplate # <-------- No '@' on 'mainHomeTemplate'

And while I'm here, you should let Backbone take care of jQuery stuff for el and your view already has @$el (assuming that you're using a recent version of Backbone) so you don't have to $(@el):

Test = Backbone.View.extend
    el: '#page'
    render: ->
        @$el.html mainHomeTemplate

I'm assuming that the lack of indentation in your define function is just a copy/paste error as well; you have to be very careful with your indentation in CoffeeScript, doubly so when pasting CoffeeScript code into a question. You can also use the normal CoffeeScript class mechanism instead of Backbone.View.extend. Your final result should look something like this:

define [
  'jquery',
  'underscore',
  'backbone',
  'text!templates/dashboard/main.html'
], ($, _, Backbone, mainHomeTemplate) ->

    class Test extends Backbone.View
        el: '#page'

        render: ->
            @$el.html mainHomeTemplate

    Test

Upvotes: 3

Related Questions