如何将此示例函数调整为Backbone

How to adapt this example function to Backbone?

本文关键字:函数 调整 Backbone      更新时间:2023-09-26

我想把这段代码重写到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提供上下文参数,因为renderappendPlot已经是绑定的方法,只需要这样做:

initialize: ->
  @collection.on('reset', @render)
  @collection.on('add', @appendPlot)