Backbone:如何通过路由器在视图中获取和显示一个模型数据

时间:2014-04-30 05:13:50

标签: javascript backbone.js routes single-page-application backbone-routing

我创建了一个非常基本的骨干应用程序,以了解它是如何工作的。

在路由器中,我只想通过在网址中传递id来显示一个模型,即用户,而不是整个集合,该怎么做?

例如,我想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???
  }
});

非常感谢。

1 个答案:

答案 0 :(得分:1)

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) });
  }