骨干路由器和视图

时间:2013-03-18 21:00:20

标签: backbone.js

我已经开始使用Backbone.js并尝试将路由转向特定的视图。在我的HTML我有<a href="#project/1">标签,用于呈现项目任务的视图。

查询

点击链接后,它会将id的任务附加到DOM,但是,当点击第二个链接时,它会将该任务附加到前一个下方。我不确定$.empty视图的最佳做法是否会调用show方法?

我的路由器的片段:

routes: {
    'project/:id: 'showtasks'
},

showtasks: function(id) {
   Event.trigger('tasks:show', id);
}

任务集的片段

initialize: function() {
    Event.on('tasks:show', this.show, this);
},

show: function() {
    var task = this.collection.get(id);
    var taskView = new App.Views.Task({ model: task });
    this.$el.append(taskView.render().el);
}

集合

var tasks = new App.Collections.Tasks([
    {
        id: 1,
        title: 'First Task',
        content: 'Lots of Content...'
    },
    {
        id: 2,
        title: 'Second Task',
        content: 'Lots of Content...'
    },
    {
        id: 3,
        title: 'Third Task',
        content: 'Lots of Content...'
    }
]);

var tasksView = new App.Views.Tasks({ collection: tasks });

1 个答案:

答案 0 :(得分:2)

Backbone视图的几个好的设计模式是:

  • 多次调用render方法不应有任何副作用。它应该正确呈现。

  • 在渲染中使用append时,基本上是在渲染方法中设置视图的流程,这应该基本上是视图模板的责任。

    < / LI>

所以我建议你应该使用这个&gt;

this.$el.html(taskView.render().el);

如果您有子视图,这将完全正常,但是您会遇到问题。对于read this - (basically this whole answer is a shameless ripoff of this article :P )

相关问题