I want to rewrite this code to Backbone.js, how should I do that?
app/assets/javascripts/views/plots/plots_index.js.coffee
class App.Views.PlotsIndex extends Backbone.View
template: JST['plots/index']
events:
'submit #new_plot': 'createPlot'
initialize: ->
@collection.on('reset', @render, this)
@collection.on('add', @appendPlot, this)
render: =>
$(@el).html(@template())
@collection.each(@appendPlot)
this
appendPlot: (plot) =>
view = new App.Views.Plot(model: plot)
@$('#all_plots').append(view.render().el)
createPlot: (event) ->
event.preventDefault()
attributes = name: $('#new_plot_name').val()
@collection.create attributes,
wait: true
success: -> $('#new_plot')[0].reset()
error: @handleError
app/assets/templates/plots/index.jst.eco
<textarea class="input" id="new_plot_name" name="name" rows="5" onClick="if(this.value == 'Type something') { this.value = ''; }">Type something</textarea>
<input class="generate_button col2" name="commit" type="submit" value="Submit" />
I want to put the function from onClick into the view code, but can’t quite figure it. I tried things like this, but no luck:
events:
'click #new_plot_name' : 'clear'
clear: =>
if @$('#new_plot_name').value == 'Type something'
@$('#new_plot_name').value = ''
What would be the way to do it, so I can do something like:
<textarea class="input" id="new_plot_name" name="name" rows="5" onClick="<%= @clear(this) %>">Type something</textarea>
I’m pretty sure the problem is in your
clearmethod.When you say
x = @$('#new_plot_name'), you get a jQuery object inx. jQuery objects generally don’t havevalueproperties the way DOM objects do; if you want to work with the value of a form element that’s wrapped in a jQuery object, you want to use thevalmethod:Then drop the
onClickattribute from your template:CoffeeScript (
@clear(this)) won’t work there, neither@northiswould be what you want in that context, andcleardoesn’t take an object argument anyway. Besides, this is Backbone so the events should be hooked up through the view’sevents.Demo: http://jsfiddle.net/ambiguous/gfK4L/
That said, people do use Tab to move around inside forms so you probably want to use a focus event (not click) to remove your placeholder and a blur event to put it back.
You should also be using a
placeholderattribute for this sort of thing; if you need to support non-HTML5 browsers then there are lots of shims and plugins that will work better than yourclearmethod. Placeholder behavior is surprising tricky to get right, for example you’ll probably be submitting a lot of forms withnamecoming through as'Type something'because you’re not checking that they really did type something in your submit handler.Also, there’s no need for
$(@el), Backbone already supplies a jQuery wrapped@elin@$el. And in yourinitialize:you don’t need to supply the context arguments to
onsincerenderandappendPlotare already bound methods, just this should do: