每当我添加template: JST["users/show"]
时在我的 Backbone View 中,我收到以下两个错误:
Uncaught ReferenceError: JST is not defined
Uncaught TypeError: Twitter.Views.UserShow is not a function
我查看了有关 stackoverflow 上未定义 JST 的所有问题,但我无法找出问题所在。我也跑了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 .
路由器.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);
}
});
用户.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;
}
});
用户.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")
返回正确的用户名。
最佳答案
问题出在链轮 gem 上。
将 Sprockets 和 Sprockets-Rails gem 保留在特定版本上,此错误应该会得到解决。
对我来说,以下版本解决了问题:
gem 'sprockets', '3.3.4'
gem 'sprockets-rails', '2.3.3', require: 'sprockets/railtie'
关于javascript - Uncaught ReferenceError : JST is not defined on Rails Backbone,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34244739/