1

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

询问

单击该链接时,它会将带有 的任务附加idDOM,但是,当单击第二个链接时,它会将该任务附加到前一个链接的下方。我不确定$.emptyView 的最佳实践是否然后调用该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 });
4

1 回答 1

2

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

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

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

所以我建议你应该使用这个>

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

这可以很好地工作,但是如果您有子视图,您会遇到问题。为此阅读-(基本上,整个答案是对本文的无耻剽窃:P)

于 2013-03-19T07:52:15.503 回答