卸载 backbone 查看和注销事件

Unload backbone view and unregister events

我正在尝试创建一个简单的编辑器,您可以在其中单击一个元素并使用简单的输入加载脚本模板,当我键入时我希望更新到 DOM 元素。问题是,如果我单击标题,则标题和介绍的介绍和开始输入文本都会更新。我怎样才能 "unload" 视图并且只让一个视图生效?

$(function() {
  window.Brick = Backbone.View.extend({
    initialize: function() {},
    render: function() {
      this.$el.mouseenter(function() {
        $(this)
          .css('outline', 'solid #467ace 1px')
          .css('outline-offset', '-1px')
          .css('cursor', 'pointer');
      }).mouseleave(function() {
        $(this)
          .css('outline', 'none')
          .css('cursor', 'default');
      });
    },
    events: {
      "click": "openEditor"
    },
    openEditor: function(event) {

      event.preventDefault();

      console.log('load editor');

      var self = this;

      self.editorView = new MyView({
        el: $('#editor-panel'),
        editorName: self.$el.attr('data-brick-name'),
        editor: self.$el
      });
    }
  });

  window.MyView = Backbone.View.extend({
    editorName: null,
    editor: null,
    initialize: function(options) {
      _.extend(this, _.pick(options, "editorName"));
      _.extend(this, _.pick(options, "editor"));
      this.render();
    },
    render: function() {
      var self = this;
      // Compile the template using underscore
      var template = _.template($('#' + self.editorName).html());
      // Load the compiled HTML into the Backbone "el"
      this.$el.html(template);
    },
    events: {
      'keyup :input': 'logKey'
    },
    logKey: function(e) {
      console.log($(this.editor).text());
      $(this.editor).text($(e.currentTarget).val());
    }
  });
});

$(function() {
  $('[data-editable="true"]').each(function(e) {
    console.log(e);
    var self = $(this);
    var brick = new Brick({
      el: self
    }).render();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>



<h1 data-editable="true" data-brick-name="heading">Lorem ipsum</h1>
<p data-editable="true" data-brick-name="intro">Lorem ipsum dolar sit amet...</p>

<div id="editor-panel">
</div>

<script type="text/template" id="heading">
  <label for="Heading">Rubrik</label>
  <input name="Heading" type="text" value="Lorem ipsum" />
</script>

<script type="text/template" id="intro">
  <label for="Intro">Intro</label>
  <textarea name="Intro">Lorem ipsum dolar sit amet...</textarea>
</script>

我认为您正在寻找 undelegateEvents。来自 the docs:

undelegateEvents; Removes all of the view's delegated events. Useful if you want to disable or remove a view from the DOM temporarily.

在 Header 视图上调用它会阻止它在其他输入处理键盘事件时对其做出反应。您可以通过 delegateEvents 重新附加事件侦听器。