2014-11-09 40 views
0

如何将此函数移植到使用coffeescript类语法?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] 
+0

只是好奇 - 什么是这里的目标。这个问题有点超出'你''问题的范围,但我很好奇 - 出于学习目的 - 你在这里做什么。 – 2014-11-09 18:01:56

+0

我有一个rails应用程序,我试图用js类来扩充ruby类而不使用客户端框架。在这种情况下,我设置了一个约定,客户端采购订单模型将自动绑定到具有特定数据属性的html元素。因此,如果我有一个页面,其中包含' new'并且我'purchase_order = new App.PurchaseOrder(1)然后'purchase_order.set(“state”,“pending”)'html元素将被更新。 – mpiccolo 2014-11-09 19:08:53

+1

这是一个WIP,但您可以在这里查看源代码:https://github.com/mfpiccolo/happy_place_demo。和演示在这里:http://happy-place-demo.herokuapp.com/purchase_orders。通过在输入字段中输入id,您可以直接编辑表格。 – mpiccolo 2014-11-09 21:05:06

回答

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回调内部将进行静态绑定,在这个例子中你的类的实例。

+0

小修正:我认为事件处理程序中this的上下文将是事件本身,而不是全局上下文。 – 2014-11-09 11:59:47

+0

@JedSchneider好吧,你可能是对的,全部取决于回调的调用方式。更新了答案,在此更精确。 – 2014-11-09 13:19:14

+0

=>是我正在寻找的。谢谢。您认为您可以将'@ attributes'更改为'this',因为我实际上想要在采购订单实例上调用'set'而不是属性对象。 – mpiccolo 2014-11-09 19:00:11

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