如何将此函数移植到使用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但是,与此类似的东西将无法工作,因为@属性不是在构造函数的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]发布于 2014-11-09 08:32:04
如果你做这样的事
@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将静态地绑定到类的实例中。
发布于 2014-11-09 18:05:18
这个怎么样:
# 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 @
returnhttps://stackoverflow.com/questions/26825995
复制相似问题