jjzjj

javascript - 没有集合的主干模型。向服务器发送重复数据?

coder 2024-07-25 原文

我有一个由 Rails 后端提供支持的 Backbone 应用程序。我有一个 Invitation 资源,我可以通过向邀请 Controller 的创建操作发送 POST 请求来发送邀请。

我的 Backbone 模型看起来像这样(coffeescript):

class Invitation extends Backbone.Model
  urlRoot: '/invitations'

发送邀请的表单模板如下。我试图让它尽可能接近普通的 rails 形式,因为看起来 Rails 会处理得最好:

<form action="/invitations" accept-charset="UTF-8" id="new_invitation" class="new_invitation" method="post">
  <input id="invitation_recipient_name" class="invitation_recipient_name" type="text" name="invitation[recipient_name]" />
  <input id="invitation_recipient_email" class="invitation_recipient_email" type="text" name="invitation[recipient_email]" />
  <input type="submit" class="btn primary" name="commit" id="invite" value="Send Invitation" />
</form>

这是该模型和模板的主干 View

class InvitationView extends Backbone.View
  # this is the template shown above
  template: JST['backbone/templates/invitation']
  events:
    'click #invite': 'sendInvite'

  render: ->
    $(this.el).html this.template()
    this
  sendInvite: (e) ->
    e.preventDefault()
    name = this.$('#invitation_recipient_name')
    email = this.$('#invitation_recipient_email')
    this.model.save
      recipient_name: name.val()
      recipient_email: email.val()

问题是,当我单击提交按钮并调用 sendInvite 方法时,我的服务器接收到具有以下结构的数据:

Parameters: {"recipient_name"=>"A name", "recipient_email"=>"name@example.com", "invitation"=>{"recipient_email"=>"name@example.com", "recipient_name"=>"A name"}}

现在这确实有效了,因为我的 invitations#create 操作需要使用以下形式的参数:params[:invitations],这是 rails 的标准。然而,名称和电子邮件在请求中被发送了两次这一事实似乎表明我的设置有问题。

我做错了什么还是正确的?

如果有人想看,这是我的 Controller 操作:

  # POST /invitations
  def create
    @invitation = current_user.sent_invitations.new params[:invitation]

    respond_to do |format|
      if @invitation.save
        format.json { render_for_api :invitation, json: @invitation, status: :created }
      else
        format.json { render json: @invitation.errors, status: :unproccessible_entity }
      end
    end
  end

编辑 如果我设置属性并在保存之前记录它,这就是我的邀请模型的样子:

  Invitation
    _changed: false
    _changing: false
    _escapedAttributes: Object
      __proto__: Object
    _previousAttributes: Object
      recipient_email: "dave@example.com"
      recipient_name: "Dave"
      __proto__: Object
    attributes: Object
      recipient_email: "dave@example.com"
      recipient_name: "Dave"
      __proto__: Object
    cid: "c17"
    __proto__: ctor

日志由以下代码生成:

sendInvite: (e) ->
    e.preventDefault()
    name = @$('#invitation_recipient_name')
    email = @$('#invitation_recipient_email')
    @model.set recipient_name: name.val(), recipient_email: email.val()
    console.log "THe model to save", @model

编辑2
这就是我在路由器中实例化 View 的方式。我应该如何更改它以便 Backbone 自动跟踪我的模型属性,即使我没有从服务器获取和设置它们?

  var TeamRouter = Backbone.Router.extend({
    routes: {
      'members': 'members'
    },

    members: function() {
      @invite = new MoveOutOrg.Models.Invitation();
      @inviteView = new MoveOutOrg.Views.InvitationView({
        model: @invite
      });
      $('#stage').append(@inviteView.render().el);
    }
  });

最佳答案

params[:recipient_name]params[:recipient_email] 字段是您调用 model.save() 的结果。传入的参数是可选的。如果已经使用正确的值创建了模型,则无需传递任何内容来保存。缺少的部分是您如何实例化 View 。

此外,我会将事件更改为 “submit #new_invitation”。它更具描述性。您关心的是提交的表单……而不是他们单击了按钮。它还捕获了他们提交表单而不单击按钮(例如按 enter 键)的情况。

要将 View 链接到模型,请使用initialize 方法。

initialize: ->
  @model.bind('change', @render)

要记住的基本事情是 model 事件通过集合冒泡并传给任何其他监听者。所以现在当你保存时,如果任何属性被更改,一个 change 事件将被触发,这将导致 View 重新呈现。

关于javascript - 没有集合的主干模型。向服务器发送重复数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7379525/

有关javascript - 没有集合的主干模型。向服务器发送重复数据?的更多相关文章

  1. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  2. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  3. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  4. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  5. ruby - 难道Lua没有和Ruby的method_missing相媲美的东西吗? - 2

    我好像记得Lua有类似Ruby的method_missing的东西。还是我记错了? 最佳答案 表的metatable的__index和__newindex可以用于与Ruby的method_missing相同的效果。 关于ruby-难道Lua没有和Ruby的method_missing相媲美的东西吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/7732154/

  6. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  7. ruby-on-rails - 在混合/模块中覆盖模型的属性访问器 - 2

    我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah

  8. ruby-on-rails - rails 目前在重启后没有安装 - 2

    我有一个奇怪的问题:我在rvm上安装了ruby​​onrails。一切正常,我可以创建项目。但是在我输入“railsnew”时重新启动后,我有“程序'rails'当前未安装。”。SystemUbuntu12.04ruby-v"1.9.3p194"gemlistactionmailer(3.2.5)actionpack(3.2.5)activemodel(3.2.5)activerecord(3.2.5)activeresource(3.2.5)activesupport(3.2.5)arel(3.0.2)builder(3.0.0)bundler(1.1.4)coffee-rails(

  9. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  10. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

随机推荐