2012-11-13 70 views
26

我想在我的收藏非RESTful的方式,所以我決定重寫Collection.fetch覆蓋骨幹的收藏取

App.carClc = Backbone.Collection.extend({ 
    model : App.cardModel, 
    url : 'http://localhost/bbtest/data.php', 
    fetch : function() { 
     $.ajax({ 
      type : 'GET', 
      url : this.url, 
      success : function(data) { 
       console.log(data); 
      } 
     }); 
    } 
}); 

我不知道怎麼我的收藏設爲響應。我是BackboneJS的新手,謝謝大家!

+0

我不明白。爲什麼寫一個自己的$ .ajax?取回的方式沒有你的代碼一樣!?!? .. – Moszeed

+6

服務器端的風格不是RESTful –

回答

56

,但不能完全覆蓋它,嘗試:

var MyCollection = Backbone.Collection.extend({ 

     //custom methods 

     fetch: function(options) { 

      //do specific pre-processing 

      //Call Backbone's fetch 
      return Backbone.Collection.prototype.fetch.call(this, options); 
     } 

    });  

在這裏,你不必推出自己的$.ajax

另外,不要在最後一行,如果你想使用由骨幹fetch方法返回的jQuery的承諾忘了return

查看http://japhr.blogspot.in/2011/10/overriding-url-and-fetch-in-backbonejs.html瞭解更多詳情。

+5

這個答案讓我感覺更加乾淨,並且允許您不會限制自己的任何其他功能.fetch()有以後可能需要使用的功能。 –

+0

這不會正確調用並創建模型。 – htmldrum

+2

@JRM可以請擴展嗎? – briangonzalez

3

我使用的是這樣的:

$.when($.ajax(URL, { dataType: "json" })) 
    .then($.proxy(function(response) { 
      ctx.view.collection.reset(response);        
    },ctx)); 

要點beeing我用collection.reset(data)重新初始化集合

+1

只是一個挑剔的問題。 $ .ajax是一個承諾,因此上面的代碼可以在$ .when()之外重新聲明,即:.ajax(...)。then(...),應該可以正常工作嗎?雖然,收集工作很好。 – seebiscuit

30

骨幹採集有兩種方法來設置添加新的數據和復位。比方說,你想輸入的數據,以取代所有收集數據,併爲此使用復位:如果你想定製的「裝飾」添加到fetch

App.carClc = Backbone.Collection.extend({ 
model : App.cardModel, 
url : 'http://localhost/bbtest/data.php', 
fetch : function() { 
    // store reference for this collection 
    var collection = this; 
    $.ajax({ 
     type : 'GET', 
     url : this.url, 
     dataType : 'json', 
     success : function(data) { 
      console.log(data); 
      // set collection data (assuming you have retrieved a json object) 
      collection.reset(data) 
     } 
    }); 
} 
}) 
+0

非常感謝。 –

+0

collection.reset(data),搜索了幾小時 – max4ever

2

如果你想保持獲取「thenable」的承諾,那麼你也可以做這樣的事情:

fetch: function() { 
    var self = this, 
     deferred = new $.Deferred(); 

    $.get(this.url).done(function(data) { 
      // parse data 
     self.reset({parsed data}); 
     deferred.resolve(); //pass in anything you want in promise 
    }); 
    return deferred.promise(); 
} 
0

如果你需要爲每個模型和/或收集爲此,覆蓋Backbone.ajax

覆蓋Backbone.ajax爲您提供的請求options通常會傳遞給$.ajax。您只需要返回$.ajax(或其他一些Promise)的響應,並且不需要擔心在集合/模型中設置東西。