首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Coffeescript转换函数为类

Coffeescript转换函数为类
EN

Stack Overflow用户
提问于 2014-11-09 07:24:07
回答 2查看 60关注 0票数 0

如何将此函数移植到使用coffeescript类语法?

代码语言:javascript
复制
App.PurchaseOrder = (uid) ->
  binder = new App.DataBinder(uid, "purchase-order")

  # Abstract all this out
  purchase_order =
    attributes: {}

    # The attribute setter publish changes using the DataBinder PubSub
    set: (attr_name, val) ->
      @attributes[attr_name] = val
      binder.trigger uid + ":change", [
        attr_name
        val
        this
      ]
      return

    get: (attr_name) ->
      @attributes[attr_name]

    _binder: binder

  # Subscribe to the PubSub
  binder.on uid + ":change", (evt, attr_name, new_val, initiator) ->
    purchase_order.set attr_name, new_val  if initiator isnt purchase_order
    return

  purchase_order

但是,与此类似的东西将无法工作,因为@属性不是在构造函数的binder.on中定义的。

代码语言:javascript
复制
class App.PurchaseOrder
  constructor: (@id) ->
    @binder = new App.DataBinder(@id, "purchase-order")
    @attributes = {}

    # Subscribe to the PubSub
    @binder.on @id + ":change", (evt, attr_name, new_val, initiator) ->
      @attributes.set attr_name, new_val  if initiator isnt @attributes
      return

  # The attribute setter publish changes using the DataBinder PubSub
  set: (attr_name, val) ->
    @attributes[attr_name] = val
    @binder.trigger @id + ":change", [
      attr_name
      val
      this
    ]
    return

  get: (attr_name) ->
    @attributes[attr_name]
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-11-09 08:32:04

如果你做这样的事

代码语言:javascript
复制
@binder.on @id + ":change", (evt, attr_name, new_val, initiator) ->
  @attributes.set attr_name, new_val  if initiator isnt @attributes
  return

然后,这意味着该函数将在全局上下文或例如事件对象的上下文中调用,但重点是this可能不指向您想要的对象。使用->代替=>

代码语言:javascript
复制
@binder.on @id + ":change", (evt, attr_name, new_val, initiator) =>
  @attributes.set attr_name, new_val  if initiator isnt @attributes
  return

然后,回调中的this将静态地绑定到类的实例中。

票数 1
EN

Stack Overflow用户

发布于 2014-11-09 18:05:18

这个怎么样:

代码语言:javascript
复制
# Subscribe to the PubSub
@binder.on @id + ":change", ((evt, attr_name, new_val, initiator) -> 
    @attributes.set attr_name, new_val  if initiator isnt @attributes ).bind @
return
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26825995

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档