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

时间:2014-04-16 09:50:40

标签: javascript jquery backbone.js backbone-views

我遇到了一个问题。我的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;

2 个答案:

答案 0 :(得分:6)

当完成诸如GET或POST之类的主干操作时,模型将触发您可以在视图上侦听的同步事件并调用您的渲染功能。该代码看起来像这样,可以放在视图初始化方法中:

this.listenTo(this.model, 'sync', this.render);

答案 1 :(得分:1)

// 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("");
    }