Html Backbone.js-页面刷新时出现错误请求错误(URL)
我正在开发一个基于主干网的webapp,它呈现一个来自web服务的可点击项目列表。单击时,表单将填充该项目的属性。我使用下划线模板将属性填充到HTML页面中。每个项目的属性都来自同一个web服务,项目ID作为URL根的额外参数。我使用如上所述的数据ID属性从单击的元素中获取ID,并使用一个函数为模型创建url,该函数将根附加此值 如果我从项目列表页面开始,这一切都会起作用,但是如果我用附加的URL(webservice/project_id)刷新特定的项目页面,我会收到一个“错误请求”错误,因为URL的项目id部分没有在模型中定义。我理解为什么会发生这种情况,但我不确定如何解决这个问题,或者我是否应该以另一种方式处理动态URL创建 以下是该型号的相关代码:Html Backbone.js-页面刷新时出现错误请求错误(URL),html,templates,url,backbone.js,underscore.js,Html,Templates,Url,Backbone.js,Underscore.js,我正在开发一个基于主干网的webapp,它呈现一个来自web服务的可点击项目列表。单击时,表单将填充该项目的属性。我使用下划线模板将属性填充到HTML页面中。每个项目的属性都来自同一个web服务,项目ID作为URL根的额外参数。我使用如上所述的数据ID属性从单击的元素中获取ID,并使用一个函数为模型创建url,该函数将根附加此值 如果我从项目列表页面开始,这一切都会起作用,但是如果我用附加的URL(webservice/project_id)刷新特定的项目页面,我会收到一个“错误请求”错误,因为
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>
<% }); %>
我确实找到了这个解决方案。它似乎可行,但有点不太对劲。我仍然对其他更清洁的解决方案感兴趣: (thisProjID是一个全局变量) 在my router for This Project model/This ProjectDetail视图中: 如果thisProjID没有值,只需添加一个检查;如果是,请从URL获取:
app_router.on('route:thisProjectDetail', function(e) {
console.log("routed to this project");
//new //
if (thisProjID == "") {
var curURL = window.location.href;
console.log(curURL);
var projNum = (curURL.substr(curURL.lastIndexOf('/') + 1));
thisProjID = projNum;
}
/////
var thisProjectData = new ThisProject();
thisProjectData.fetch(
{ success : onThisDataHandler, error: onThisErrorHandler }
).then(function(response){
var _ThisProjectDetailView = new ThisProjectDetailView({model: thisProjectData,
el: $("#myprojects")
});
console.log(thisProjectData);
});
});
这些视图是在哪里创建的?更新位置..的代码在哪里。。?你需要的是一个主干路由器。路由器应该正在创建视图并处理位置。您从哪里获取收藏?@TJ我有路由,请参阅我的编辑above@vini我正在获取路由事件上的集合,请参阅已编辑的代码above@TJ你看到我的编辑了吗?我找到了一个简陋的解决方案,但我想要更干净的
app_router.on('route:thisProjectDetail', function(e) {
console.log("routed to this project");
//new //
if (thisProjID == "") {
var curURL = window.location.href;
console.log(curURL);
var projNum = (curURL.substr(curURL.lastIndexOf('/') + 1));
thisProjID = projNum;
}
/////
var thisProjectData = new ThisProject();
thisProjectData.fetch(
{ success : onThisDataHandler, error: onThisErrorHandler }
).then(function(response){
var _ThisProjectDetailView = new ThisProjectDetailView({model: thisProjectData,
el: $("#myprojects")
});
console.log(thisProjectData);
});
});