[英]How to refresh a view/template in Backbone.js
我遇到了一個問題。 我的CommentinfoModel
正在從服務器獲取數據,我能夠在視圖中顯示所有數據。 我使用另一個PostwallModel
在同一個視圖中發布數據。
當我發布數據時,我收到了服務器的響應,但該數據沒有出現在模板中。 當我轉到另一個頁面並返回時,會出現新發布的數據。 完成發布操作后如何刷新。 這是我的代碼:
var myPostwallView = Backbone.View.extend({
el: $("#content"),
events: {
'click #postinwall': 'postmessage',
},
initialize: function () {
var that = this;
var options = {
query: uni_id + "/chaid/" + currentChallenge['id']
}
var onDataHandler = function (collection) {
that.render();
}
var onErrorHandler = function (collection) {
var errorstring = JSON.stringify(collection);
console.log(errorstring);
}
this.model = new CommentinfoModel(options);
this.model.fetch({
success: onDataHandler,
error: onErrorHandler,
dataType: "json"
});
},
render: function () {
$('.nav li').removeClass('active');
$('.nav li a[href="' + window.location.hash + '"]').parent().addClass('active');
var data = {
cinfo: this.model.toJSON(),
_: _
};
var compiledTemplate = _.template(PostwallTemplate, {
data: data
});
this.$el.html(compiledTemplate);
},
// Posting message action
postmessage: function (e) {
var optionsp = {
query: uni_id + "/chaid/" + currentChallenge['id']
}
var postmsg = $('#txt').val();
var obj = new PostwallModel(optionsp);
obj.save({
uid: uni_id,
chaid: currentChallenge['id'],
post: postmsg
}, {
success: function (obj, response) {
console.log(response.responseText, console.log(response);
alert(response.message));
}
});
e.preventDefault();
$('#txt').val("");
}
});
return myPostwallView;
當 GET 或 POST 等主干操作完成時,模型將觸發同步事件,您可以在視圖上偵聽該事件並調用渲染函數。 該代碼看起來像這樣,可以放在您的視圖初始化方法中:
this.listenTo(this.model, 'sync', this.render);
// Posting message action
postmessage: function (e) {
var optionsp = {
query: uni_id + "/chaid/" + currentChallenge['id']
}
var postmsg = $('#txt').val();
var obj = new PostwallModel(optionsp);
obj.save({
uid: uni_id,
chaid: currentChallenge['id'],
post: postmsg
}, {
success: function (obj, response) {
console.log(response.responseText, console.log(response);
alert(response.message),that.initialize());
}
});
e.preventDefault();
$('#txt').val("");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.