我开始使用 Backbone.js 进行开发。 而且我仍然不知道如何使用最佳实践编写代码。
我的应用程序正在运行,但有一些问题,例如比较器不起作用。
我真的会帮助他变得更好。
查看:
Todos.Views.TasksView = Backbone.View.extend({
template: JST['todos/index'],
tagName: 'div',
id: '#todos',
initialize: function () {
this.collection = new Todos.Collections.TasksCollection();
this.collection.fetch({
reset: true
});
this.render();
this.listenTo(this.collection, 'reset', this.render);
this.listenTo(this.collection, 'change', this.render);
this.listenTo(this.collection, 'sort', this.render);
},
render: function () {
$(this.el).html(this.template({
tasks: tasks[0].task
}));
return this;
}
});
集合:
Todos.Collections.TasksCollection = Backbone.Collection.extend({
model: Todos.Models.TasksModel
url: "/api/tasks.json",
comparator: function (sort) {
return -(new Date(sort.get('eventTime'))).getTime();
},
parse: function (response) {
return response;
}
});
型号:
Todos.Models.TasksModel = Backbone.Model.extend({
parse: function (response, options) {
return response;
}
});
路由器:
Todos.Routers.TasksRouter = Backbone.Router.extend({
routes: {
'': 'index'
},
initialize: function () {
var viewTasks = new Todo.Views.TasksView({
model: Todos.Models.TasksModel,
el: '.tasks-list'
});
}
});
应用程序.js:
window.Todos = {
Models: {},
Collections: {},
Views: {},
Routers: {},
initialize: function () {
new Todos.Routers.TasksRouter();
Backbone.history.start({})
},
$(document).ready(function () {
Todos.initialize();
});
最佳答案
在你的 View 中尽量不要有模型或集合函数,如获取、保存或设置。这不是 View 的责任。
示例:不要在集合中使用 this.collection.fetch(),而是执行类似的操作。
this.collection = new Todos.Collections.TasksCollection();
this.collection.getSomething();
this.render();
this.listenTo(this.collection, 'reset', this.render);
this.listenTo(this.collection, 'change', this.render);
this.listenTo(this.collection, 'sort', this.render);
在您的集合中,添加一个方法来执行“fetch()”请求。 我不明白你为什么要声明解析函数..你没有做任何事情.. 当我想在主干将 JSON 中的某些内容绑定(bind)到模型/集合之前更改它时,我喜欢使用解析函数。
我看不到您在哪里调用比较器函数。也许“sort”参数的值无效。
在你的模型中你再次使用解析..我看不出原因。
你的路由器没问题。 我喜欢你的代码..对于初学者来说,正如你所说。真的很好。
我建议您使用低破折号而不是下划线...它有更多处理数组的选项。
尝试使用require.js来加载你的js依赖..这会对你有很大帮助。 www.requirejs.org
希望有帮助。
关于javascript - 如何改进我的 Backbone 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24438999/