繁体   English   中英

如何在 Backbone.js 中刷新视图/模板

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM