Search code examples
domspine.js

Spine.js get associated controller from element


I got an html-element aside.sidebar with an associated spine.js controller.

class App.Sidebar extends Spine.Controller
  tag: 'aside'
  className: 'sidebar'

how do i get the controller from the element? something like this:

con = $("aside.sidebar").spineController().someControllerMethod()

I'm using jquery + spine.js.


Solution

  • I've looked through the controller source code and it doesn't look like there is a built-in way to access the controller from the element (https://github.com/spine/spine/blob/dev/src/spine.coffee#L482). What I do is make a global variable to hold the controller so that I can access it from other places:

    app = new App()
    
    # inside of App constructor:
    @foo_widget = new App.FooWidgetController()
    
    # from other non-spine code:
    app.foo_widget.method()
    

    Another option would be to do the association yourself using jquery's data() method:

    class App.FooWidgetController
      constructor: ->
        super
        @el.data 'controller', this
    
    # from other code:
    $('#widget').data('controller').method()