由于某些原因,我的代码需要一些帮助,我无法让我的 View 在模型更改后重新呈现。
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
从父 View 被触发时。这将启动一个 $.ajax
请求。最后,这会带回我想分配给使用 ResultLoanView
的关联模型的数据。由于某种原因,模型没有被更改,因为 initialize
中的监听器没有重新呈现我的 html。我的目标是将数据重新分配给我的模型,该模型将根据 initialize
中的监听器重新呈现。有什么想法吗?
最佳答案
我相信你需要打电话。
that.model.set(data.response)
而不是直接更改.attributes
。文档提到了 set()
的更改事件。
还有一个旁注,查看 this.listenTo()
与 model.on()
之间的区别。许多实例最好使用 listenTo 来防止内存泄漏。
关于javascript - 在 Backbone 中的 AJAX 请求中模型更改后重新呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31363820/