我想将此代码重写为 Backbone.js,我该怎么做?
应用程序/资产/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" />
我想将 onClick 中的函数放入视图代码中,但不太清楚。我尝试过这样的事情,但没有运气:
events:
'click #new_plot_name' : 'clear'
clear: =>
if @$('#new_plot_name').value == 'Type something'
@$('#new_plot_name').value = ''
这样做的方法是什么,所以我可以做类似的事情:
<textarea class="input" id="new_plot_name" name="name" rows="5" onClick="<%= @clear(this) %>">Type something</textarea>