简体   繁体   中英

Uncaught ReferenceError: JST is not defined on Rails Backbone

Whenever I add template: JST["users/show"] in my Backbone view, I get these two errors: Uncaught ReferenceError: JST is not defined Uncaught TypeError: Twitter.Views.UserShow is not a function

I looked at all of the questions regarding JST is not defined on stackoverflow but I'm couldn't figure out the problem. I also ran rails g backbone:install

Here are my files

application.js

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require underscore
//= require backbone
//= require twitter
//= require_tree ../templates
//= require_tree ./models
//= require_tree ./collections
//= require_tree ./views
//= require_tree ./routers
//= require_tree .

router.js

Twitter.Routers.Router = Backbone.Router.extend({

  initialize: function (options) {
    this.$rootEl = options.$rootEl;
    this.users = new Twitter.Collections.Users ();
  },

  routes: {
    'users/:id': 'userShow'
  },

  userShow: function(id) {
    var user = this.users.getOrFetch(id);
    var showView = new Twitter.Views.UserShow ({
      model: user
    });

    this.$rootEl.html(showView.render().$el);
  }

});

user.js

Twitter.Collections.Users = Backbone.Collection.extend ({

  url: '/api/users',
  model: Twitter.Models.User,

  getOrFetch: function (id) {
    var user = this.get(id);
    var users = this;
    if (user) {
      user.fetch();
    } else {
      user = new Twitter.Models.User ( {id: id });
      user.fetch({
        success: function () {
          users.add(user)
        }
      });
    }

    return user;
  }

});

user.js

Twitter.Models.User = Backbone.Model.extend ({

  urlRoot: '/api/users'

});

show.js

Twitter.Views.UserShow = Backbone.View.extend ({

  template: JST["users/show"],

  initialize: function () {
    this.listenTo(this.model, 'sync', this.render);
  },

  render: function () {
    // console.log(this.model.get("username"))
    var content = this.template({ user: this.model });
    this.$el.html(content);

    return this;
  }

});

show.jst.ejs (this is inside templates/users)

<%= user.escape("username") %>

console.log(this.model.get("username") returns the correct username.

I had to add config.assets.paths << "app/assets/templates" inside of

module TwitterClone
  class Application < Rails::Application

    config.active_record.raise_in_transactional_callbacks = true
    config.assets.paths << "app/assets/templates"
  end
end

The problem is with the Sprockets gem.

Keep the Sprockets and Sprockets-Rails gems on a specific version and this error should get resolved.

For me the following versions fixed the problem:

gem 'sprockets', '3.3.4'
gem 'sprockets-rails', '2.3.3', require: 'sprockets/railtie'

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