2014-11-25 50 views
0

我試圖摧毀一個模型,我得到「遺漏的類型錯誤:未定義是不是一個函數」當我打電話this.model.destroy({}選項)型號破壞返回undefined不是一個函數

我模式是這樣的:

window.CompanyModel = Backbone.Model.extend({ 

     initialize: function() { 
      console.log('CompanyModel:initialized'); 
     }, 

     parse: function(response, options) { 
      return response; 
     }, 

    }); 

收藏:

window.CompaniesCollection = Backbone.Collection.extend({ 

     model: window.CompanyModel, 

     initialize: function() { 
      console.log('CompaniesCollection:initialized'); 
     }, 
    }); 

查看:

window.CompaniesView = Backbone.View.extend({ 
     initialize : function() { 
      console.log('CompaniesView:initialized'); 
      this.companies = new CompaniesCollection(); 
      this.companies.url = function(id) { 
       return '../src/rest/administration/companies/companies'; 
      }; 
      this.company = new CompanyModel(); 
     }, 
     [...more code...] 
     confirmDeleteForm : function(event) { 
      event.preventDefault(); 

      var company_id = $('#company_existing').val(); 
      var self=this; 
      this.company = this.companies.where({'company_id':company_id}); 

      this.company.destroy({ 
       wait: true, 
       success: function(model, response) { 
        console.log('deleted'); 
        $('#deleteModal').modal('hide'); 
        self.cleanForm(); 
        self.getCompanies(); 
       }, 
       error: function(model, response) { 
        console.log('error'); 
        console.log(model); 
        console.log(response); 
        console.log(options); 
        if (response.status == 500) { 
         self.showErrorMessage('Se produjo un error en el servidor', 'ERROR'); 
        } else { 
         self.showErrorMessage(response.responseText, 'ATENCION'); 
        } 
       } 
      }); 

     }, 

任何幫助,將不勝感激。

問候,LN

回答

4

this.companies.where返回一個數組,從fine manual

wherecollection.where(attributes)

Return an array of all the models in a collection that match the passed attributes.

這意味着,這樣的:

this.company = this.companies.where({'company_id':company_id}); 

留下一個陣列中this.company和數組沒有destroy方法。

如果在this.companies只有一個條目匹配{company_id: company_id},那麼你可以說:

this.company = this.companies.where({'company_id':company_id})[0]; 
// -----------------------------------------------------------^^^ 

或者你可以使用findWhere

​​

說:

this.company = this.companies.findWhere({'company_id':company_id}); 

如果是這種情況,那麼你的company_id在貢可能是真正爲企業的唯一的標識符,那麼你可能要在模型中idAttribute設置爲company_id

window.CompanyModel = Backbone.Model.extend({ 
    idAttribute: 'company_id', 
    //... 

,這樣你可以使用Collection#get找到它沒有搜索。

+0

非常感謝。 – leandronn 2014-11-25 05:02:14