0

I've been experimenting a little bit and have run into a few occasions where it seems to make sense to apply a CS "class" via a loop.

For example:

if ($areas = $('.itemParent')).length >= 1
    class SomeClass
        constructor: (el) ->
            @$parent = el
            @$overflow = el.find('.overflow')
            @$items = @$overflow.find('.item')

            @max = @$items.length - 1
            @current = 0

        # Gets us to an area
        goToItem: (i) ->
            @$overflow.animate
                scrollLeft: @$items.eq(i).position().left
            , 450, 'easeInOutQuad'

        # Binds each item
        bindItems: ->
            @$parent.find('.item').bind 'click tap', (e) =>
                el = $(e.target).parents('.item')

                @$items.removeClass('active')
                el.addClass('active')

                @goToItem(el.index())
            @

    # Iterate and apply the structure to all areas
    $areas.each -> 
        area = new SomeClass($(@))
        area.bindItems()

It just seems more structured than binding them all "globally".. Is this a poor way to do this?

7
  • few occasions where it seems to make sense Please list these occasions. Commented Nov 21, 2012 at 20:34
  • Multiple 'slideshows' on a page, for example. Commented Nov 21, 2012 at 20:35
  • You mean multiple instances of the slide show class? Commented Nov 21, 2012 at 20:35
  • Basically. Like if I have ".slideshow" on a website in multiple areas, and they all have different slides/pagers/navs (but are similarly structured). Applying the class would autoplay/bind/etc on each. Just seems like a DRY approach? Commented Nov 21, 2012 at 20:37
  • That's fine but why do you need to re-declare the class functions each time too? Commented Nov 21, 2012 at 20:39

1 Answer 1

1

The idea behind Coffeescript classes is to define them globally or in modules.

Defining a class inside of another type of scope is kind of missing the point.

Coffeescript classes encourage a more ruby-esque view of classes as being separate from instances while retaining the power you get from being able to apply them as you see fit.

To put it simply, it's best to use Coffeescript classes at the top level or by exporting and requiring them from modules.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.