2013-04-03 89 views
2

我一直在我的頭上撞牆在這一個幾個小時.... 看着許多的一頁,我覺得我有我的腳本正確,但我的收藏在fetch方法中傳遞的add:true不會觸發add事件。我可以綁定到復位事件,但添加事件不會觸發..骨幹集合沒有觸發添加事件取得

型號:

test.Models.AppBlock = Backbone.Model.extend({ 
    defaults: { 
     AppID:   null, 
     AppName:  null, 
     AppDescription: null 
    }, 
    idAttribute: "AppID" 
}); 

收藏:

test.Collections.AppBlock = Backbone.Collection.extend({ 
    model:  test.Models.AppBlock, 
    url:   ApiPath + "apps/byuser", 

    Loading: false, 

    initialize: function() { 

    }, 

    getAppBlocks: function() { 
     if (!this.Loading) { 
      this.Loading = true; 
      this.fetch({ 
       data: JSON.stringify({ 
          Token: test.Session.Token 
         }), 
       add:   true, // OMG WTF ?!?! 
       type:  'POST', 
       dataType: 'json', 
       contentType: 'application/json', 
       cache:  false, 
       success:  this.getAppBlocksSuccess, 
       error:  this.getAppBlocksError 
      }); 
     } 
    }, 

    parse: function (response) { 
     return response.Data; 
    }, 

    getAppBlocksSuccess: function (that, response) { 

    }, 

    getAppBlocksError: function (that, response) { 

    } 
}); 

查看:

test.Views.DashboardLatestMain = Backbone.View.extend({ 
    Loading: null, 

    initialize: function() { 
     this.template = _.template(test.Templates.DashboardLatestMain); 
     this.collection.bind('add', this.addAppBlock); 
     this.render(); 
    }, 

    render: function() { 
     $('#latest').prepend(this.template); 
     this.Loading = new test.Views.Loading({ 
      el: '.main' 
     }); 
     this.collection.getAppBlocks(); 
    }, 

    addAppBlock: function (appBlockModel) { 
     alert(appBlockModel); // no dice.... 
     var appBlockView = new test.Views.AppBlock({ 
      model: appBlockModel, 
      el: '#latest .main h3', 
      After: true 
     }); 
    } 
}); 

任何非常感謝幫助。

編輯

數據從API返回:

{ 
    "Status":["1","OK"], 
    "Data":[{"AppID":1,"AppName":"test","AppDescription":"test"}, 
      {"AppID":2,"AppName":"test","AppDescription":"test"}] 
} 
+0

我們可以有更多關於你打電話回來的信息嗎?模型添加到集合中,但不會觸發「添加」事件? – Loamhoof

+1

您使用BB 1.0嗎?如果不是,則需要使用'update:true',因爲在1.0之前,默認值是重置而不是更新,只觸發'重置'事件並且不會觸發'添加'事件。 –

+0

@MikaelHärsjö我看不到你的觀點。他從服務器獲取數據,他爲什麼要使用set? – Loamhoof

回答

9

骨幹0.9.9集合的fetch做了reset默認情況下,它只能引發 '復位' 事件。在1.0中,提取會執行update(現在稱爲set),並默認觸發「添加」,「刪除」和「更改」事件。

因此,要麼更新到1.0,您的現有代碼應該可以工作。或者,將update:true添加到您的fetch通話中(您不需要add:true,那麼因爲這是默認設置)。

+0

我繼續前進並更新到1.0,但addAppBlock方法沒有得到傳遞給它的模型..呃..我現在嘗試this.collection.on('add',this.addAppBlock)。我們會看到..再次感謝你! –

+0

嗯,不知道這是爲什麼:[http://backbonejs.org/#Events-catalog](http://backbonejs.org/#Events-catalog) –

+0

沒關係..只是永遠不理我。我沒有將模型的屬性傳遞給模板。 –