简体   繁体   中英

Coffeescript class return element passed into constructor

I'm rewriting a personal coffeescript project to use classes as much as possible, just for the lulz (and also because it helps auto generating documentation), and I've run into something I might not be able to write as a class and wanted to see if anyone has a solution or if its just impossible.

I want to take a html element and add a bunch of custom methods to it, something similar to the following works:

myelement = (element) ->
  element.method1 = ->
  element.method2 = ->
  element

raw = $('#something')[0]
out = myelement(raw)
expect(out).toBe(raw)
expect(out.method1).toBeDefined()

But as I said, I would like to write it as a class, like so:

class MyElement
  constructor: (element)
    #something funny here
  method1: ->
  method2: ->

raw = $('#something')[0]
out = new MyElement(raw)
expect(out).toBe(raw)
expect(out.method1).toBeDefined()

With the goal to be able to treat the returned object as either a html element or as an instance of my class.

Is this possible without crazy hacks or should I take a different approach, or just leave it and stick with what I have already?

Don't think that is possible 'without crazy hacks' as CoffeeScript doesn't allows you to change @ ( this ) and fails to compile otherwise you could do:

class MyElement
  constructor: (element) ->
    element.test = 5
    @ = element

But you sill have some options to consider. First you can encapsulate your modified object and return it from method like so:

class MyElement
  constructor: (element) ->
    @myElement = element
    @myElement.test = 5
  get: =>
     @myElement

myElement = (new MyElement($('body')[0])).get()
console.log(myElement == $('body')[0])
console.log(myElement.test)

JsFiddle

Or you can go with some 'manual' class implementation:

MyElement = (->
  MyElement = (element) ->
    element.test = 5
    element
  MyElement
)()

myElement = (new MyElement($('body')[0]))
console.log(myElement == $('body')[0])
console.log(myElement.test)

JsFiddle 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM