0

我正在使用模型從使用POST的服務中獲取位置數據。 但是我很努力地讓視圖聽到這個模型,當它最終收到響應時。骨幹視圖聽模型,沒有改變或重置觸發?

注意我已經覆蓋了一些模型方法來適合我正在使用的服務。

型號代碼

 define([ 
     'underscore', 
     'backbone', 
    ], function (_, Backbone) 
    { 
     'use strict'; 

     //model class declaration 
     var LocationsModel = Backbone.Model.extend({ 

      locations: null, //this attribute stores the json response 


      //url for http post to get location data 
      url: '/testserver/getLocationData', 

      /** 
       @name constructor 
       @method initialise 
      **/ 
      initialize: function() 
      { 
       console.log("Location Model - Initialize"); 
       this.fetchLocationData(); 
      }, 

      /** 
       @name fetchLocationData 
       @method fetchLocationData 
       @summary retrieves bulding/location data from service, overriden fetch function to use POST 
      **/ 
      fetchLocationData: function() 
      { 
       console.log("Location Model - Fetching Building/Location data from EAS"); 

       this.fetch({ 
        data: JSON.stringify({ "lastRefreshedDateTime": "2015-04-01T08:18:06.000+00:00", "uid": "" }), //refactor this - string literals which are static currently 
        type: "POST", 
        contentType: "application/json", 
        async : false, //this is bad but it is the only way I can get it to work 

at the moment 
       reset: true //tried adding reset parameter but no luck 
      }); 
     }, 

     /** 
      @name parse 
      @method parse 
      @summary parse is a method inside backbone that can be overridden, in this override we set a model attribute to the JSOn response 
     **/ 
     parse: function (response, xhr) 
     { 
      console.log("Location Model - Parsing response from EAS"); 
      this.attributes = { "true": true }; //tried adding an attribute value to trigger "change:true" 
      this.locations = response; 
      //do other stuff 
     }, 


    }); 

     return LocationsModel; 

    }); 

在視圖初始化器我曾嘗試以下結合並聽取模型但他們似乎並沒有響應後觸發。

查看代碼

model : new LocationModel(), 

     initialize: function() 
    { 
     console.log("Filter View - Initialize"); 
     this.render(); 
     this.listenTo(this.model, 'change', this.render); //this only fires at the start when the model is initialised 
     this.model.on('change', this.render, this); //same as above 
     this.listenTo(this.model, 'reset', this.render); //not fired at all 
    }, 

對於集合這是相當簡單的聽所發生的任何變化,但它似乎是一個不同的球類比賽爲骨幹機型。

TLDR,我怎樣才能讓視圖聽取模型成功的獲取請求?

回答

1

sync事件是你想要的listenTo。一旦fetch成功完成,它就會被解僱。骨幹源中的這條線是罪魁禍首:Backbone source, line 578

現在您的代碼應該是這個樣子:

查看代碼

model : new LocationModel(), 

    initialize: function() 
{ 
    console.log("Filter View - Initialize"); 
    this.render(); 
    this.listenTo(this.model, "sync", this.render); 
}, 

這裏有一個fiddle這說明你的代碼工作。我用httpbin來模擬POST請求。您現在也可以在取回請求中刪除async: false參數:)(我已經在小提琴示例中將其刪除)。