我创建了一个非常基本的主干应用程序,以了解它是如何工作的。
在路由器中,我只想通过在 url 中传递 id 来显示 1 个模型,即一个用户,而不是整个集合,该怎么做?
例如,我想要执行 someapp.com/app/#user/2
,这只会显示用户 no2 的详细信息。
请参阅我的作品jsfiddle
// router
var ViewsRouter = Backbone.Router.extend({
routes: {
'': 'viewOne',
'one': 'viewOne',
'two': 'viewTwo',
'user/:id': 'user'
},
viewOne: function() {
var view = new TheViewOne({ model: new TheModel });
},
viewTwo: function() {
var view = new UserView({ model: new TheModel });
},
user: function(id) {
// how to get just 1 user with the corresponding id passed as argument
// and display it???
}
});
非常感谢。
最佳答案
https://github.com/coding-idiot/BackboneCRUD
我已经为初学者编写了一个完整的 Backbone CRUD,没有后端内容。下面是part我们从集合中获取用户并显示/渲染它。
查看
var UserEditView = Backbone.View.extend({
render: function(options) {
if (options && options.id) {
var template = _.template($("#user-edit-template").html(), {
user: userCollection.get(options.id)
});
this.$el.html(template);
} else {
var template = _.template($("#user-edit-template").html(), {
user: null
});
// console.log(template);
this.$el.html(template);
}
return this;
},
路由器
router.on('route:editUser', function(id) {
console.log("Show edit user view : " + id);
var userEditView = new UserEditView({
el: '.content'
});
userEditView.render({
id: id
});
});
更新
特别是,坚持你的代码,路由器将看起来像这样:
user: function(id) {
var view = new UserView({ model: userCollection.get(id) });
}
关于javascript - Backbone : how to get and display just one model data in a view via router,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23380144/