1

I am a complete noob with Backbone, I've only been learning it for about 8 hours now, so sorry if this question seems basic. The documentation isn't very clear on this.

The model in question, Product, needs to run a lot of Ajax calls. Within the logic of my model, I need to run at least 2 Ajax calls within the validation of a model depending on certain conditions.

Not only that, but when certain fields change I also need to run Ajax calls as each field triggers its own change field bubbled from the last change, i.e.:

  • A price changes
  • The model recalcs the price of the product form a server call
  • At the same time a change is triggered on the supplier variable of the model from the price change
  • The supplier change must do an Ajax call AFTER the price change.

So what I need to know is: Basically how should I go about converting all my Ajax calls to Backbone? What is the best method here?

dda
  • 6,030
  • 2
  • 25
  • 34
Sammaye
  • 43,242
  • 7
  • 104
  • 146
  • You can't do async validation in the `validate` method. It's designed and intended entirely for client side work (https://github.com/documentcloud/backbone/issues/233). – WiredPrairie Mar 25 '13 at 10:56
  • @WiredPrairie though at the end of the thred it does say " If you'd like to perform a server-side validation, feel free. Just run the validation before you change the client-side state by calling set()." so it should be OK for those models which are a bit more complex, I have also seen a work around using save here: http://stackoverflow.com/questions/11331604/backbone-js-ajax-calls – Sammaye Mar 25 '13 at 11:04
  • Yes, all true. I wanted to point out that you couldn't use `validate` in a natural way, and that you'll need to build your own prevalidate logic. – WiredPrairie Mar 25 '13 at 11:07

1 Answers1

0

I am going to answer this with my findings and solutions.

So I have completed the backbone integration with all of the Ajax calls. The way I solved this was to use the promise API of jQuery to return a deferred object from model functions which could be used for chaining. I then in my interface used this functions in a chained manner.

To explain better here is an example:- imagine I have two functions within a class of Product; one called populateRecord and the other set_price. Each does their own Ajax call and processing.

Within the view ProductView I would house a function called edit which would process the logic of how and when these two model functions should be called like so:

this.model.populateRecord().then(function(data){ return $this.model.set_price(data) })

The method of putting the "business" aspect of this into the view works well and solves many problrms.

Hopefully this helps others,

Sammaye
  • 43,242
  • 7
  • 104
  • 146