javascript - How to handle multiple invalid events being fired from collection.create() in backbone.js -


i adding model using collection.create method. have over-ridden model.validate method , error window pops correct error messages.

everything seems work great until click save button third of fourth time. invalid event gets fired every previous invalid model. noticed collection did not clean after when invalid event fired added line model.collection.pop() hoping solve it.

the invalid event still fired off n number of times. n being number of times have attempted create new model until reload app. found should display error message if model being passed in has collection object on it. , works seems bit janky.

i tried adding model.stoplistening() inside invalid event method. no luck though. assume has me not cleaning these partial or invalid models.

createnewasset: (event) ->  @collection.on "invalid", (model, error) =>       console.log "invalid fired"       unless model.collection undefined         errview = new myapp.views.error(collection: error)         $("body").append(errview.render().el)         model.collection.pop()   @collection.on "sync", ->    backbone.history.navigate("assets", true)   @collection.create     name: @$el.find("#new_asset_name").val() 

clarification update:

the above code works end user, have zombie models or collections firing off n number of events. n being number of times user has clicked save button.

i don't think problem have stray models, problem you're binding new anonymous "invalid" callback collection every time createnewasset called.

you should bind "invalid" , "sync" handlers once in initialize:

initialize: ->   # still use anonymous functions here.   @listento(@collection, 'invalid', @bad_model)   @listento(@collection, 'sync',    @synced)   #...  bad_model: (model, error) ->   console.log('invalid fired')   #...  synced: ->   backbone.history.navigate('assets', true) 

and createnewasset becomes this:

createnewasset: (event) ->   @collection.create     name: @$('#new_asset_name').val() 

i switched @$el.find() @$() standard built in short cut @$el.find.


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -