AJAX 中的模型更改后重新渲染 Backbone 中的请求

Rerendering after model change in AJAX request in Backbone

由于某些原因,我的代码需要一些帮助,我无法让我的视图在模型更改后重新呈现。

    var ResultLoanView = Backbone.View.extend({
      id:"result",
      initialize: function(){
        this.render();
        this.on('submissionMade',this.getData,this)
        this.model.on('change',this.render,this)
      },

      template: _.template("<% _.each(models, function(data,index) { %><div><%= index %></div> <%= data %><% }); %>"),

      getData: function(){
             var that = this;
             $.ajax({
              type: "GET",
              url:"http://zillow.com/webservice/mortgage/CalculateAffordability.htm?",
              data: {
                "zws-id":"APIKEY",
                annualincome: 1000000,
                monthlypayment: 2000,
                down: 800000,
                monthlydebts: 1500,
                rate: 6.504,
                schedule: "yearly",
                term: 360,
                debttoincome: 36,
                incometax: 30,
                propertytax: 20,
                hazard: 20000,
                pmi: 1000,
                output: "json"
              },
              dataType: "jsonp",
              success: function(data) {
                that.model.attributes = data.response
                console.log(that.model)
                  }
              ,
              error: function(result) {
                  alert("Error");
              }
          })
      },
      render:function(){
        console.log("rerender")
        var need = this.$el.html(this.template({models:this.model.toJSON()}))
        $('body').append(need)

      }

    })

因此,当 submissionMade 从父视图触发时。这会启动 $.ajax 请求。最后,这带回了我想用 ResultLoanView 分配给关联模型的数据。出于某种原因,模型没有被更改,因为 initialize 中的侦听器没有重新呈现我的 html。我的目标是将数据重新分配给我的模型,该模型将根据 initialize 中的侦听器重新渲染。有什么想法吗?

我相信你需要打电话。

that.model.set(data.response)

而不是直接更改 .attributes。文档提到 set().

的更改事件

另外,请查看 this.listenTo()model.on() 之间的差异。许多实例最好使用listenTo来防止内存泄漏。