如何将此函数移植到使用coffeescript类语法?
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
根据这一点,但这不起作用,因为@attributes未在构造函数的binder.on中定义。
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]
答案 0 :(得分:1)
如果你这样做
@binder.on @id + ":change", (evt, attr_name, new_val, initiator) ->
@attributes.set attr_name, new_val if initiator isnt @attributes
return
然后它意味着将在全局上下文中或在例如上下文中调用该函数。事件对象,但关键是this
可能不指向您想要的对象。而不是->
使用=>
@binder.on @id + ":change", (evt, attr_name, new_val, initiator) =>
@attributes.set attr_name, new_val if initiator isnt @attributes
return
然后回调中的this
将静态绑定,在此示例中为您的类的实例。
答案 1 :(得分:0)
怎么样:
# 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