【发布时间】:2016-04-06 20:26:38
【问题描述】:
我正在开发一个基于 Backbone 的 web 应用程序,它呈现来自 web 服务的项目的可点击列表。单击时,将使用该项目的属性填充表单。我正在使用下划线模板将属性填充到 HTML 页面中。每个项目的属性都来自同一个 Web 服务,项目 ID 作为 URL 根的额外参数。我使用here 中描述的 data-id 属性从单击的元素中获取 ID,并使用一个函数为模型创建 url,该函数将根附加到该值。
如果我从项目列表页面开始,这一切都有效,但如果我使用附加的 URL (webservice/project_id) 刷新特定项目页面,我会收到“错误请求”错误,因为 URL 的项目 ID 部分模型中没有定义。我了解为什么会发生这种情况,但我不确定如何解决这个问题,或者我是否应该以其他方式处理动态 URL 创建?
这里是模型的相关代码:
var ThisProject = Backbone.Model.extend({
initialize: function() {
...
},
url: function(){
thisProjURL = 'http://XX.XXX.XX/api/projects/' + thisProjID;
return thisProjURL;
}, ....
这是视图,其中包含可点击项目的列表:
var ListProjectView = Backbone.View.extend({
events: {
'click a': 'getId'
},
initialize: function() {
this.render();
},
render: function() {
var template = _.template(myprojecttpl);
this.$el.html(template({collection: this.collection.toJSON()}));
},
getId: function(e){
thisProjID = $(e.currentTarget).data("id");
},
});
这是 HTML 文件中带有下划线变量的相关行:
<% _.each(collection, function(model) { %>
<li><a href="#/thisproject-detail/<%= model.Pid %>" data-id="<%= model.Pid %>"><%= model.PjctName %></a></li>
<% }); %>
下面是路由代码:
var AppRouter = Backbone.Router.extend({
routes: {
"" : "index", // this is where the list of projects is displayed
"login": "login",
"logout": "logout",
"project-detail": "projectDetail",
"thisproject-detail/:Pid": "thisProjectDetail", // this is the specific project
"project-search": "projectSearch",
"treatment-search": "treatmentSearch"
}
});
// Initiate the router
var app_router = new AppRouter;
app_router.on('route:index', function() {
var _projectCollection = new ProjectCollection();
_projectCollection.fetch(
{ success : onDataHandler, error: onErrorHandler }
).then(function(response){
var _ListProjectView = new ListProjectView({ collection: _projectCollection ,
el: $("#myprojects")
});
});
});
app_router.on('route:thisProjectDetail', function(e) {
var thisProjectData = new ThisProject();
thisProjectData.fetch(
{ success : onThisDataHandler, error: onThisErrorHandler }
).then(function(response){
var _ThisProjectDetailView = new ThisProjectDetailView({model: thisProjectData,
el: $("#myprojects")
});
});
});
【问题讨论】:
-
这些视图是在哪里创建的?更新位置的代码在哪里..?您需要的是骨干路由器。路由器应该创建视图并处理位置。
-
你在哪里获取你的收藏?
-
@TJ 我有路由,请参阅上面的编辑
-
@vini 我正在获取有关路由事件的集合,请参阅上面的编辑代码
-
@TJ 你看到我的编辑了吗?我找到了一个 hacky 解决方案,但我想要更干净的解决方案
标签: html templates url backbone.js underscore.js