如何改进我的Backbone代码

时间:2014-06-26 19:49:00

标签: javascript backbone.js

我开始在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'
      });
  }
});

App.js:

window.Todos = {
    Models: {},
    Collections: {},
    Views: {},
    Routers: {},
    initialize: function () {
       new Todos.Routers.TasksRouter();
       Backbone.history.start({})
    },


$(document).ready(function () {
    Todos.initialize();
});

1 个答案:

答案 0 :(得分:1)

在您的视图中尝试不具有模式或集合功能,如获取或保存或设置。这不是视图责任。

示例:不要在集合中包含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中的内容时使用parse函数。

我无法看到你在哪里调用比较器功能......也许是排序''参数的值无效。

在您的模型中,您再次使用解析...我无法找到原因。

你的路由器还可以。 我喜欢你的代码......正如你所说,对于初学者。它非常好。

我建议您使用lo-dash而不是下划线...它有更多选项可以使用数组。

尝试使用require.js加载你的js依赖项..它会帮助你很多。 www.requirejs.org

希望它有所帮助。