Skip to content

Instantly share code, notes, and snippets.

@bradstewart
Created April 14, 2014 18:07
Show Gist options
  • Save bradstewart/10670247 to your computer and use it in GitHub Desktop.
Save bradstewart/10670247 to your computer and use it in GitHub Desktop.
Batman.js View from Model accessor
# This started as "why can't data-partial also take a keypath," but I actually
# like having a Batman.View which can attach jQuery plugins and stuff for each
# activity that's added.
class App.FeedActivity extends Batman.Model
# ...
@accessor 'show', ->
@layout('show')
@accessor 'create', ->
@layout('create')
layout: (viewType) ->
html = "feed_activities/#{@get('type')}/_#{viewType}"
new App.FeedActivityView( source: html, activity: this )
<!-- Somewhere in HTML where you want to display the activity feed -->
<ul data-foreach-activity="currentUser.feedActivities">
<li data-view="activity.show"></li>
</ul>
@rmosolgo
Copy link

This is very cool! I've never thought of using something like this. I can imagine implementing something like this on model:

class Batman.ViewDirectory extends Batman.Object
  constructor: (@model) ->
    # just stores the model class for later...

  @accessor (partialPath) ->
    # eg "assets/html/animals/show"
    source = Batman.Navigator.normalizePath(Batman.config.pathToHTML, @modelresourceName,  partialPath)
    viewClass = somehowLookupViewClass || Batman.View
    # this doesn't add `record: record` -- but the record will still be in the scope of the rendered view
    viewInstance = new viewClass({source})
class Batman.Model extends Batman.Object
  # create a view directory for the class
  @accessor 'views', => new Batman.ViewDirectory(@)

Then you could do stuff like

<div data-view='animal.views.show'></div>

@rmosolgo
Copy link

Although one thing to consider would be that the same Batman.View is getting rendered over and over, right? You haven't run into any weirdness with that?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment