从控制器传递错误消息以使用Backbone查看

时间:2014-02-05 10:53:12

标签: javascript backbone.js

我有以下错误消息可用HTML:

<div class="alert alert-error">
    <div class="content">
        <p>
             <i class="fa fa-warning"></i>
            User not found.
        </p>
    </div>
</div>

如何在Backbone中为没有失去良好做法的用户显示该内容?

我的意思是,让我的视图以可靠性呈现它的最佳方法是什么?

何时显示此消息?

user.save({}, {
  success: function(model, response) {
    if (response.error) {
      // hey, the message goes here!
    }
  }
});

2 个答案:

答案 0 :(得分:2)

您可以使用新方法扩展Backbone View以显示如下错误:

_.extend(Backbone.View.prototype, {
    showError: function(message) {
        // Here you render your error, may be like this : $('#errorInfo').html(message);
    }
});

并在您看来:

var self = this; // I assume that you are in the view
user.save({}, {
  success: function(model, response) {
    if (response.error) {
      self.showError(/* things you want to pass */);
    }
  }
});

答案 1 :(得分:1)

对我来说,最佳做法是创建一个对象 errorMessageView

HTML:

<div id="errorInfo"></div>

JS:

var errorMessageView = Backbone.View.extend({
    el: "#errorInfo",
    initialize: function() {
    },
    renderInnerHTML: function(message) {
            this.el.innerHTML = message;
    }
});

var errorMessage = new errorMessageView ;

user.save({}, {
    success: function(model, response) {
      if (response.error) {
        errorMessage.renderInnerHTML(response.error);
      }
    }
});