1

我想将此代码重写为 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>
4

1 回答 1

1

我很确定问题出在你的clear方法上。

clear: =>
  if @$('#new_plot_name').value == 'Type something'
    @$('#new_plot_name').value = ''

当你说x = @$('#new_plot_name'),你得到一个 jQuery 对象x。jQuery 对象通常没有valueDOM 对象那样的属性;如果您想使用包装在 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/


也就是说,人们确实Tab习惯于在表单内移动,因此您可能希望使用焦点事件(而不是单击)来删除占位符并使用模糊事件将其放回原处。

您还应该placeholder为这类事情使用属性;如果您需要支持非 HTML5 浏览器,那么有很多 shims 和插件会比您的clear方法更好。占位符行为很难正确处理,例如,您可能会提交很多表单,name因为'Type something'您没有检查它们是否确实在您的提交处理程序中输入了某些内容。

此外,不需要$(@el).Backbone 已经提供了一个 jQuery 包装@el@$el. 在你的initialize

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

您不需要提供 context 参数给onsincerender并且appendPlot已经是绑定的方法,应该这样做:

initialize: ->
  @collection.on('reset', @render)
  @collection.on('add', @appendPlot)
于 2012-09-02T19:09:59.103 回答