2012-07-21 177 views
0

没有实例我有一个骨干模型,像这样骨干模型收集

define([ 
'underscore', 
'backbone' 
],function(_,Backbone) { 
    var Task = Backbone.Model.extend({ 
     //api url 
     url:'', 

     methodToURL: { 
     'read': './api/tasks/index', 
     'create': './api/tasks/task', 
     'update': './api/tasks/task', 
     'delete': './api/tasks/task' 
     }, 
     sync: function(method, model, options) { 
      options = options || {}; 
      options.url = this.methodToURL[method.toLowerCase()]; 

      Backbone.sync(method, model, options); 
     } 
    }); 
    return Task; 
}); 

和收集

define(['underscore','backbone','models/task'],function(_,Backbone,Task) { 
    var TaskCollection = Backbone.Collection.extend({ 
     //Model 
     model:Task, 
     //api url 
     url:'', 

     methodToURL: { 
     'read': './api/tasks/index', 
     'create': './api/tasks/task', 
     'update': './api/tasks/task', 
     'delete': './api/tasks/task' 
     }, 

     sync: function(method, model, options) { 
      options = options || {}; 
      options.url = this.methodToURL[method.toLowerCase()]; 

      Backbone.sync(method, model, options); 
     }, 
     //construct 
     initialize: function() { 
      this.sort_key = 'end'; 
      this._model = new Task(); 
      this.fetch(); 
     }, 

     comparator: function(a,b) { 
      a = a.get(this.sort_key); 
      b = b.get(this.sort_key); 
      return a > b ? 1 
       : a < b ? -1 
       :   0; 
     }, 

     mark_complete: function(task_id) { 
      var task_status = 0; 
        console.log(this.model); 
      this.model.save({id:task_id,task_status:task_status}); 
     }, 

     mark_incomplete: function(task_id) { 
      var task_status = 1; 
        console.log(this.model); 
      this.model.save({id:task_id,task_status:task_status}); 
     }, 

     sort_by_status: function() { 
      this.sort_key = 'task_status'; 
      this.sort(); 
     }, 

     sort_by_task_tag: function() { 
      this.sort_key = 'task_group'; 
      this.sort(); 
     } 
    }); 
    return TaskCollection; 
}); 

当我mark_complete方法运行模式登录到控制台,但它记录这 “function(){ parent.apply(this, arguments); }”和说“function(){ parent.apply(this, arguments); } has no method 'save'”; 我猜测模型应该被实例化,所以集合可以访问它的方法,所以什么是错的?

回答

2

model属性只是Collection在将模型添加到集合时使用的构造函数。它旨在让您的生活更轻松,当您尝试向收藏集输入数据时。在将Task模型添加到TaskCollection时,您不必总是调用构造函数,而只需输入一个JavaScript对象,它将执行相同的操作。

因此,这是你的代码是什么样子就像当你想插入模型没有model属性设置为您TaskCollection

taskCollection.add(new Task({ 
    name: "Get Milk", 
    description: "We're out of milk. There's a sale going on at the local supermarket." 
})); 

// If you wanted to just input just the JSON object without calling the 
// constructor, then you can't. 

这是你的代码是什么样子,如果你喜欢曾设置model属性

taskCollection.add({ 
    name: "Get Milk", 
    description: "We're out of milk. There's a sale going on at the local supermarket." 
}); 

正如你所看到的,你不需要调用Task构造函数; TaskCollection的实例会为你打电话。

这就是为什么TaskCollection的实例只会将model属性设置为Task的实际构造函数,而不是初始化版本。