我想把这段代码重写到Backbone.js,我应该怎么做?
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" />
我想把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>
我很确定问题出在clear
方法中。
clear: =>
if @$('#new_plot_name').value == 'Type something'
@$('#new_plot_name').value = ''
当您说x = @$('#new_plot_name')
时,您会在x
中得到一个jQuery对象。jQuery对象通常不像DOM对象那样具有value
属性;如果要处理包装在jQuery对象中的表单元素的值,则需要使用val
方法:
clear: =>
if @$('#new_plot_name').val() == 'Type something'
@$('#new_plot_name').val('')
然后从模板中删除onClick
属性:
<textarea class="input" id="new_plot_name" name="name" rows="5">Type something</textarea>
CoffeeScript(@clear(this)
)在那里不起作用,@
和this
在该上下文中都不是您想要的,而且clear
无论如何都不接受对象参数。此外,这是Backbone,因此应该通过视图的events
连接事件。
演示:http://jsfiddle.net/ambiguous/gfK4L/
也就是说,人们确实使用选项卡在表单内移动,所以你可能想使用焦点事件(而不是单击)来删除占位符,并使用模糊事件将其放回。
对于这类事情,您还应该使用placeholder
属性;如果你需要支持非HTML5浏览器,那么有很多垫片和插件会比你的clear
方法工作得更好。占位符行为令人惊讶地难以正确处理,例如,您可能会提交很多name
为'Type something'
的表单,因为您没有检查他们是否真的在提交处理程序中键入了内容。
此外,不需要$(@el)
,Backbone已经在@$el
中提供了一个jQuery封装的@el
。在你的initialize
:
initialize: ->
@collection.on('reset', @render, this)
@collection.on('add', @appendPlot, this)
您不需要向on
提供上下文参数,因为render
和appendPlot
已经是绑定的方法,只需要这样做:
initialize: ->
@collection.on('reset', @render)
@collection.on('add', @appendPlot)