Backbone.js使用嵌套待办事项的Todo示例

时间:2012-07-02 12:25:45

标签: javascript backbone.js

我想在每个待办事项上使用嵌套待办事项扩展backbone todo examplecode)。

我是否必须使用Backbone关系,还是有更好或更简单的解决方案?

Edit1:我尝试使用Backbone关系来使它工作但我在应用程序视图中的“createOnEnter”函数中收到错误:“Uncaught TypeError:Object function(obj){return new wrapper(obj);} has没有方法'isObject'“。这是代码:

$(function(){

// ------------------- Todo Model ------------------

var Todo = Backbone.RelationalModel.extend({

  relations: [{
     type: Backbone.HasMany,
     key: "children",
     relatedModel: "Todo",
     collectionType: "TodoList",
     reverseRelation: {
         key: "parent",
         includeInJSON: "id"
     } 
  }],

initialize: function() {
  console.log("MODEL: initialize()");
  if (!this.get("order") && this.get ("parent")) {
    this.set( {order: this.get("parent").nextChildIndex() });
  }
},

defaults: function() {
    console.log("MODEL: defaults()");
  return { 
      done: false,
      content: "default content" };
},

nextChildIndex: function() {
    var children = this.get( 'children' );
    return children && children.length || 0;
},

clear: function() {
  this.destroy();
}
});

// ------------------- Todo Collection ------------------

var TodoList = Backbone.Collection.extend({
model: Todo,
// Save all of the todo items under the `"todos"` namespace.
localStorage: new Store("todos-backbone"),

done: function() {
  return this.filter(function(todo){ return todo.get('done'); });
},

});
var Todos = new TodoList;

// ------------------- Todo View ------------------

var TodoView = Backbone.View.extend({
tagName:  "li",

template: _.template($('#item-template').html()),

events: {
  "keypress input.add-child": "addChild",
  "click .check"              : "toggleDone",
  "dblclick label.todo-content" : "edit",
  "click span.todo-destroy"   : "clear",
  "keypress .todo-input"      : "updateOnEnter",
  "blur .todo-input"          : "close"
},

initialize: function() {
    console.log("TODOVIEW: initialize()");
  this.model.bind('change', this.render);
  this.model.bind('destroy', this.remove);

  this.model.bind("update:children", this.renderChild);
  this.model.bind("add:children", this.renderChild);

  this.el = $( this.el );
  this.childViews = {};
},

render: function() {
  console.log("TODOVIEW: render()");
  $(this.el).html(this.template(this.model.toJSON()));
  this.setText();
  this.input = this.$('.todo-input');

  this.el.append("<ul>", {"class": "children"}).append("<input>", { type: "text", "class": "add-child" });

  _.each(this.get("children"), function(child) {
      this.renderChild(child);
  }, this);      
    return this;
},

  addChild: function(text) {
      console.log("TODOVIEW: addChild()");
      if (e.keyCode == 13){
          var text = this.el.find("input.add-child").text();
          var child = new Todo( { parent: this.model, text: text});
      }
  },

  renderChild: function(model){
      console.log("TODOVIEW: renderChild()");
    var childView = new TodoView({ model: model});
    this.childViews[model.cid] = childView;
    this.el.find("ul.children").append(childView.render());
  },

// Remove the item, destroy the model.
clear: function() {
    console.log("TODOVIEW: clear()");
  this.model.set({parent: null});
  this.model.destroy();
  //this.model.clear();
}
});

// ------------------应用程序------------------------ < / p>

var AppView = Backbone.View.extend({
el: $("#todoapp"),

statsTemplate: _.template($('#stats-template').html()),

events: {
  "keypress #new-todo":  "createOnEnter",
  "keyup #new-todo":     "showTooltip",
  "click .todo-clear a": "clearCompleted",
  "click .mark-all-done": "toggleAllComplete"
},

initialize: function() {
    console.log("APPVIEW: initialize()");
  _.bindAll(this, 'addOne', 'addAll', 'render', 'toggleAllComplete');

  this.input = this.$("#new-todo");

  Todos.bind('add',     this.addOne);
  Todos.bind('reset',   this.addAll);
  Todos.bind('all',     this.render);

  Todos.fetch();
},

render: function() {

},

addOne: function(todo) {
  var view = new TodoView({model: todo});
  this.$("#todo-list").append(view.render().el);
},

addAll: function() {
  Todos.each(this.addOne);
},

// Generate the attributes for a new Todo item.
newAttributes: function() {
  return {
    content: this.input.val(),
    order:   Todos.nextOrder(),
    done:    false
  };
},

createOnEnter: function(e) {
    console.log("APPVIEW: createOnEnter()");
  if (e.keyCode != 13) return;
  Todos.create( this.newAttributes());
  this.input.val('');
},
});
var App = new AppView;
});

2 个答案:

答案 0 :(得分:2)

在这种情况下,我被分配了一个待办事项集合到新的 类别模型属性

喜欢:

var todo = Backbone.Model.extend({

    defaults:function(){
        return {description:"No item description",done:false };
    },
    ...............
    ............... 
});

var todo_collection = Backbone.Collection.extend({
    model: todo,
    ..............
    ..............
});

var Category = Backbone.Model.extend({
    initialize: function(){
        this.toDoCollection = new todo_collection();
    }
});

如果你需要更多参考,请参阅我在github上的例子:todo list with nested items使用BACKBONE JS

答案 1 :(得分:1)

我只是将模型设置为另一个模型的属性。在你的情况下:

window.app.Todo = Backbone.Model.extend({

        // Default attributes for the todo.
        defaults: {
            title: "empty todo...",
            completed: false
        },

        // Ensure that each todo created has `title`.
        initialize: function() {
            if (!this.get("title")) {
                this.set({"title": this.defaults.title});
            }
        if(this.has("childrecords")){
            var self = this;
            self.set("children",new Array());
            $.each(this.get("childrecords"), function(id, child){
                self.get("children").push(new Todo(child));
            });
        }
    },
// ...

关于此的几点说明:

  • 我假设所有孩子都是通过名为“childrecords”
  • 的数组中的JSON加载的
  • 我使用jQuery迭代这个数组,使用你喜欢的任何东西
  • 您可能想要使用集合而不是数组