如何在 BackboneJS 中的视图元素上绑定事件?

How to bind event on view element in BackboneJS?

我正在尝试在 div(位于 backbone 视图内)上绑定点击事件

这是我创建视图并为其设置事件的代码

dialogModel = new Dialog.SimpleWindowModel({
                title: 'export:export.dialog.title',
                data: {
                    message: 'export:export.dialog.message',
                    downloadPDF: 'export:export.dialog.downloadPDF',
                    shareByQRCode: 'export:export.dialog.shareByQRCode',
                    sendEmail: 'export:export.dialog.sendEmail',
                },
                bodyTemplate: exportTpl,
            });

dialogView = new Dialog.WindowView({ model: dialogModel });

dialogView.on('click .download-pdf', function () {console.log("ff");});
dialogView.on('click .share-qr-code', ExportAction.shareByQRCode);
dialogView.on('click .send-email', ExportAction.sendEmail);

这是视图模板:

<div class="export-button-container">
  <div class="btn export-button download-pdf">
      <img src="https://betanews.com/wp-content/uploads/2015/09/PDF.jpg"/>
      <p class='dialog-message' data-i18n>{{downloadPDF}}</p>
  </div>
  <div class="btn export-button share-qr-code">
      <img src="https://www.qrstuff.com/images/sample.png"/>
      <p class='dialog-message' data-i18n>{{shareByQRCode}}</p>
  </div>
  <div class="btn export-button send-email">
      <img src="https://d1hoh05jeo8jse.cloudfront.net/media/google/gmail-icon.jpg"/>
      <p class='dialog-message' data-i18n>{{sendEmail}}</p>
  </div>
</div>

我预计当我点击 div 时 class="download-pdf", console.log("ff");将被执行,但它没有。

如何解决这个问题? 谢谢

on method is only intended for use with internal Backbone events such as add or remove, not DOM events such as click. For DOM events you have to use View's events hash/method 可以在自定义视图中指定 class 或作为选项传递给视图构造函数。

对于您的代码,视图 class 定义被遮挡,您可以使用第二个选项(传递给构造函数):

dialogView = new Dialog.WindowView({
    model: dialogModel,
    events: {
        'click .download-pdf': function () {console.log("ff");},
        'click .share-qr-code': ExportAction.shareByQRCode,
        'click .send-email': ExportAction.sendEmail
    }
});