【问题标题】:Zendesk Apps: How to create Event listeners after app was initialised?Zendesk 应用程序:如何在应用程序初始化后创建事件侦听器?
【发布时间】:2015-05-26 13:28:56
【问题描述】:

我目前正在开发一个以brand_field_id 作为其参数之一的应用程序。它将保存“品牌”的自定义票证字段 ID。问题是:它不是必要的,因为用户可能想要或不使用它提供的功能。预期行为:

  • 如果此字段填充了 ID,则将在自定义字段上添加其 .change 的事件侦听器(并且事情将完成);
  • 如果留空,则不会发生任何事情。这意味着用户选择不使用它。

Zendesk 已经为Custom Ticket Field change event 提供了完美的监听器,它的工作方式如下(动态使用brand_field_id):

events: {
  "ticket.custom_field_ticket.custom_field_{{brand_field_id}}.changed": "myCustomFieldChangedFunction"
}

...如果 brand_field_id 为空时应用程序没有崩溃,那将是非常棒的。

因为如果brand_field_id 留空,我不希望应用程序崩溃,我想在添加事件侦听器之前对其进行验证,但没有设法完成。我在app.created 事件中尝试了以下代码的几种变体,但均未成功。

if(!_.isEmpty(this.setting('brand_field_id'))){
  console.log('Brand change event added');
  this.events['ticket.custom_field_ticket.custom_field_{{brand_field_id}}.changed'] = 'brandChangedHandler';
}

console.log 被解雇,因此验证正常。不幸的是,该事件永远不会为自定义字段触发。

所以我的问题是:我如何随时随地添加事件监听器?还是有其他方法可以实现我的需要?


我什至posted about this in Zendesk's community 在一个类似的帖子上,但到目前为止还没有答案。我发现的解决方法实际上工作,但我不是很喜欢它:

events: {
  // [...]
  '*.changed': 'anyFieldChangedHandler'
},
// [...]
anyFieldChangedHandler: function(e){
  // If the changed field was {brand_field_id}
  if(!_.isEmpty(this.setting('brand_field_id')) && e.propertyName === 'ticket.custom_field_'+ this.setting('brand_field_id')){
    this.brandChangedHandler(e);
  }
},

它太宽泛了,只要更改工单上的任何字段就会触发。我想找到一个更好、更干净、更优雅的解决方案。

【问题讨论】:

  • 嗨 Michael,你能简单地用 jQuery 绑定一个新的事件监听器,如下所示 - this.$(‘.some-element-in-app’).on(‘click’, function() { /* do some thing. */ }),用你需要的元素替换元素吗?

标签: javascript events frameworks zendesk


【解决方案1】:

我知道要找到与 Zendesk 应用程序框架相关的答案是多么困难,我也处于同一条船上。

我会做这样的事情

events: {
  "ticket.custom_field_ticket.custom_field_{{brand_field_id}}.changed":"itChanged"
},
itChanged: function(){
      if(ticket.custom_field_ticket.custom_field_{{brand_field_id}} !== null && ticket.custom_field_ticket.custom_field_{{brand_field_id}} !== undefined){
          //Your custom field exists and has a value. Do something with it.
      }
      else{
          //Your custom field does not exist and/or does not have a value. do nothing
      }
}

这样的东西对您的应用有用吗?我不确定这是否与!_.isEmpty() 具有相同的功能,但您可以尝试一下。我在我的应用程序中经常使用它,有时只是作为一种安全措施,以防我的应用程序加载速度快于实际票证,这会导致应用程序加载时某些值“未定义”。

希望对你有帮助

【讨论】:

  • 感谢您的回复,确实有时很难找到您需要的东西。无论如何,我看到关于您的代码的两个问题:1)将"ticket.custom_field_ticket.custom_field_{{brand_field_id}}.changed" 注册为事件是我问题中问题的一部分:它会引发 JS 错误:Uncaught Error: Syntax error, unrecognized expression: {{brand_field_id}}.changed。 2) 在“itChanged”函数中,ticket.custom_field_ticket.custom_field_{{brand_field_id}} 不求值,甚至不是有效的 JS 语法。该表达式作为事件侦听器进行评估,因为框架解析字符串。
  • 关于上面的问题1),我的意思是如果该字段留空(根本没有值)会引发错误。
猜你喜欢
  • 2017-01-31
  • 2012-11-17
  • 2014-04-23
  • 1970-01-01
  • 2019-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多