Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 带有嵌套Todo的Backbone.js Todo示例_Javascript_Backbone.js - Fatal编程技术网

Javascript 带有嵌套Todo的Backbone.js Todo示例

Javascript 带有嵌套Todo的Backbone.js Todo示例,javascript,backbone.js,Javascript,Backbone.js,我想在每个todo项上使用嵌套的todo扩展() 我是否必须使用关系骨干网,或者是否有更好或更简单的解决方案 Edit1:我试图使用关系主干使其工作,但在应用程序视图中的“CreateOnner”函数上出现错误:“未捕获的TypeError:Object函数(obj){返回新包装器(obj);}没有方法“isObject”。代码如下: $(function(){ // ------------------- Todo Model ------------------ var Todo = B

我想在每个todo项上使用嵌套的todo扩展()

我是否必须使用关系骨干网,或者是否有更好或更简单的解决方案

Edit1:我试图使用关系主干使其工作,但在应用程序视图中的“CreateOnner”函数上出现错误:“未捕获的TypeError:Object函数(obj){返回新包装器(obj);}没有方法“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();
}
});
//--------待办事项收集------------------

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;
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();
}
});
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;
});
//--------待办事项视图------------------

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;
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();
}
});
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;
});

我只是将一个模型设置为另一个模型的属性。就你而言:

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));
            });
        }
    },
// ...
关于这一点,请注意:

  • 我假定所有子项都是通过JSON加载到一个名为“childrecords”的数组中的
  • 我使用jQuery来迭代这个数组,可以使用任何您喜欢的方法
  • 您可能希望使用集合而不是数组

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

比如:

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上的示例:使用主干JS

,如果您能了解带有添加和删除功能的集合的外观,那就太好了。我想,使用这种方法,添加或删除注释后,注释集合视图不会完全呈现,对吗?您可以很好地呈现它。但是,您无法享受像
事件
这样的收藏带来的好处。这将不会触发重新渲染。或者我应该更好地使用主干关系吗?它会在一个单独的存储中为childrecords存储一个额外的集合,还是只将所有的childs保存在模型的嵌套属性中?我还没有使用。但它似乎使用了一个child属性。它所做的是为生成的模型映射和事件