每当我在Backbone视图中添加template: JST["users/show"]
时,我都会遇到以下两个错误:
Uncaught ReferenceError: JST is not defined
Uncaught TypeError: Twitter.Views.UserShow is not a function
我查看了关于JST的所有问题都没有在stackoverflow上定义,但是我无法找出问题所在。我也跑了rails g backbone:install
这是我的文件
的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(这是模板/用户内部)
<%= user.escape("username") %>
console.log(this.model.get("username")
会返回正确的用户名。
答案 0 :(得分:0)
我必须在
中添加config.assets.paths << "app/assets/templates"
module TwitterClone
class Application < Rails::Application
config.active_record.raise_in_transactional_callbacks = true
config.assets.paths << "app/assets/templates"
end
end
答案 1 :(得分:0)
问题在于Sprockets gem。
将Sprockets和Sprockets-Rails gems保留在特定版本上,此错误应该得到解决。
对我来说,以下版本解决了这个问题:
gem 'sprockets', '3.3.4'
gem 'sprockets-rails', '2.3.3', require: 'sprockets/railtie'