I'm using brunch to work with backbone and I'm having issues with event.preventdefault(). It works initially, but after a page change it stops working.
I have a view that passes a param to the template and according to that the page is rendered. This page has multiple forms, and loads up one according to the param. All the forms have preventdefault bound to the submit buttons, but for some reason, after I switch forms using one of the nav links, the preventdefault stops working and the form gets posted. Any idea why this is the case? Let me know if you need to see code.
An example of how this happens: I click 'submit story' nav link and type something and hit submit. I get the js alert and nothing happens. Now I click 'submit poem' and click submit, but this time the form gets posted. If I started off with 'submit poem' it works fine. It also works if I click 'submit poem' and hit refresh before submitting. Weird....
EDIT: Added Code Sample. Template renders acording to the passed in type.
class exports.ClientsSettingsView extends UberView
id: 'settings_view'
className: 'view_container'
events:
'submit #credit_card_form' : 'addCard'
'submit #profile_pic_form' : 'processPicUpload'
'submit #edit_info_form' : 'test'
'click #delete_card' : 'deleteCard'
render: (type="info",status=0) ->
$('.spinner#submit').hide()
@ReadUserInfo()
$(@el).html clientsSettingsTemplate {type,sta开发者_如何学Gotus}
@FadeIn()
@
addCard: (e) ->
e.preventDefault()
$el = $(e.currentTarget)
attrs =
card_number: $el.find('#card_number').val()
card_code: $el.find('#card_code').val()
card_expiration_month: $el.find('#card_expiration_month').val()
card_expiration_year: $el.find('#card_expiration_year').val()
options =
success: (response) ->
alert "Added"
error: (e) ->
alert "Error"
model = new app.models.paymentprofile
model.save attrs, options
console.log attrs
How are you loading the additional forms and submit buttons later on? if you are dynamically pulling them in, your event may no longer be attached. You could try binding your event to the form submit using jquery's live method.
.live()
I had the same problem.
A workaround
is to manually call delegateEvents() after the Backbone.View is added to the DOM.
The issue
I was calling subview.remove()
which removes all DOM event listeners (via jQuery.remove) and used that same subview instance later on.
A solution
If a View has to remain active but must be temporary hidden use this.$el.hide()
& this.$el.show()
In other situations don't reuse Backbone.View instances, but instantiate new
ones.
精彩评论