2012-07-21 174 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的實際構造函數,而不是初始化版本。