[英]How to refresh a view/template in Backbone.js
I am running into an issue.我遇到了一个问题。 My CommentinfoModel
is fetching data from the server and I am able to show all the data in a view.我的CommentinfoModel
正在从服务器获取数据,我能够在视图中显示所有数据。 I used another PostwallModel
to post the data in same view.我使用另一个PostwallModel
在同一个视图中发布数据。
When I am posting the data, I get a response from the server, but that data does not appear in template.当我发布数据时,我收到了服务器的响应,但该数据没有出现在模板中。 When I go to another page and I come back, the new posted data is appears.当我转到另一个页面并返回时,会出现新发布的数据。 How can I refresh after my post action in done.完成发布操作后如何刷新。 Here is my code:这是我的代码:
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;
When a backbone operation such as a GET or POST is completed, the model will fire a sync event that you can listen to on the view and call your render function.当 GET 或 POST 等主干操作完成时,模型将触发同步事件,您可以在视图上侦听该事件并调用渲染函数。 That code looks something like this and can be placed in your view initialization method:该代码看起来像这样,可以放在您的视图初始化方法中:
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.