-
Notifications
You must be signed in to change notification settings - Fork 3
Presenters: Basic Functionality
Presenters are how you control what happens to your server side template once they're transported from your rails app.
To get started with Presenters simply use the presenter generator
rails g transponder:presenter [name]
Lets supposed that you are working with contacts
Let [name] be contacts
This will create a presenter contacts_presenter.coffee
in your asset's application/presenters
folder. It will also add the new Application.Presenters.ContactsPresenter()
in initializers/boot.coffee
This should get you started with presenters
Once you've generated your presenter you can start using it. How? For example lets assume that we're working with contacts_controller.rb
in your rails app.
Normally when you use Rails UJS in your index.js.erb
you would have something like this.
$('#contacts').html("<%= j render @contacts "%>);
This will return javascript code that will be executed on the client. However to use transponder instead of doing this you would do something like this
["#contacts", "<%= xms_event %>", "<%= j render @contacts %>"]
This what we call a 'transmission' in Transponder basically we are returning the element we want to work on from the server and the content in the third element in the array.
The second element <%= xms_event %>
will determine which presenter should be responsible for all this content. It usually renders out to something like this ujs:application:contacts:index
. We will cover more on this later.
For now lets take a look at how we can use that transmission.
in your ContactsPresenter on your client you would simply do something like this
class Application.Presenters.ContactsPresenter extends Transponder.Presenter
presenterName: 'contacts'
module: 'application'
index: ->
$(@element).html(@response)
The first 3 line in the above example were pre generated lets focus on the index
action. Basically the index function in this class will give you @element
which is what you put in from the server as #contacts
and the @response
is the server side template rendered by rails. In index
you would just do what you would normally do in index.js.erb
with the Rails UJS basically manipulate the DOM with the content returned from the server.
Doing things like this allow your code to be cleaner and safer. Responses returned as a 'transmission' is safe from cross site leak.