Modifying your urls on the fly using the request method with sync in backbone.js

Yeah that’s a long title, Backbone provides one default url for all your types of request with your models. But what if you want to be able to change your url model that is synching with your api depending of the type of request? Well that’s what we are here to do.

Backbone Sync

Sync is a nice utility used by backbone when you request your server to sync your model. Each time your request a change, backbone call sync, for you it is basically an empty shell for doing operations before the request is launched.

What we will do here is create 3 urls depending if we edit, create, or delete a model. To that end we will add a new function that with handle 3 new urls in your model definition:

methodUrl:  function(method){
	if(method == "delete"){
    		return "http://www.api.com/mymodel/" + this.attributes.id+"/delete";
    	}else if(method == "update"){
                return "http://www.api.com/mymodel/" + this.attributes.id+"/update";
        }else if(method == "create"){
                return "http://www.api.com/mymodel/create";
        } 
    	return false;
}

That’s nice, but from where these methods come? Well they come from backbone, backbone tells you what type of action is happening in sync, so to that end we will have to modify sync:

sync = function(method, model, options) {
    if (model.methodUrl && model.methodUrl(method.toLowerCase())) {
      	options = options || {};
      	options.url = model.methodUrl(method.toLowerCase());
    }
   Backbone.sync(method, model, options);
}

Sync is really nice, it provides you a lot of information, here we check if our methodUrl function returns an url and override our current one, and if it does not? Well it just lets the default url alone and continues normally.

Using sync globally

You could define your sync method on each model separately but that would be a pain, instead a nice idea is to apply it to every model modifying the backbone model prototype:

    Backbone.Model.prototype.sync = function(method, model, options) {
    	if (model.methodUrl && model.methodUrl(method.toLowerCase())) {
      		options = options || {};
      		options.url = model.methodUrl(method.toLowerCase());
    	}
   		Backbone.sync(method, model, options);
  	}

And there you go!

Cedric Dugas is a front-end veteran with more than 9 years under the belt, between his open source projects & entrepreneurial ambitions he is a product architect at CakeMail. Why don't you follow him on twitter.

74 Comments on "Modifying your urls on the fly using the request method with sync in backbone.js"

  1. joaquinfreshoutus says:

    This blog is awesome, please keep up the good work, we use Backbone in our apps and your articles have been very helpful :)

  2. Javier says:

    Nice! Tks!!!

  3. Nicole says:

    Hi there, its pleasant post on the topic of media print, we all be aware of media
    is a wonderful source of data.

  4. org.gr says:

    Hi, this weekend is pleasant in favor of me, as this occasion i
    am reading this wonderful educational article here at
    my home.

  5. Robbie says:

    Excellent site you have here.. It’s difficult to find high quality writing like yours these days. I truly appreciate people like you! Take care!!

    Also visit my web page – bed bugs (Robbie)

  6. Haley says:

    I intended to write you a very little observation to thank you
    once again over the pretty

    pointers

    you’ve provided on this website. It is simply
    shockingly open-handed of people like you to make without restraint
    what some people could

    possibly have marketed for an electronic book to
    make some cash for

    their own end, certainly considering the

    fact that you could possibly have

    tried it in the event you wanted. The pointers

    additionally acted to be a fantastic way to know that some people

    have the identical desire the same as my very own
    to learn whole lot more with respect to this condition.

    I’m sure there are thousands of more fun situations ahead for individuals that check out your
    blog post.

  7. Christel says:

    You can certainly see your skills in the work you

    write. The sector hopes for even more passionate writers such as you who

    are not afraid to mention how they believe. At all times follow your heart.

  8. C’est infiniment un bonheur de venir sur votre site
    web

  9. I’ve been surfing online greater than 3 hours as of late, but I by no means found any attention-grabbing article like yours.
    It’s beautiful price enough for me. Personally, if all web owners and bloggers made excellent content as you probably did, the web will probably be much
    more useful than ever before.

  10. Zachery says:

    Just dropped off a fare from the airport. BOTH: Wait a minute.
    There are many ways to advertise products of limousine services.
    It’s a new role that’s been created due to a restructure and he says to the nurse, he says that the vast majority of
    situations, obviously, it will be rolled out throughout 2013.
    When Ms Diller was not feeling well and needed to go to the gym, yoga
    class and the sport’s field, to what to limousine wear under work or evening and weekend hobbies, mothers
    also spend £1, 714.

    My web-site :: web page (Zachery)

  11. Every weekend i used to go to see this web page, for the reason that i
    want enjoyment, as this this web site conations really fastidious funny data too.

  12. Hi there! Do you know if they make any plugins to safeguard against hackers?
    I’m kinda paranoid about losing everything I’ve worked hard on. Any
    tips?

  13. Thank you for the good writeup. It in fact used
    to be a amusement account it. Look complicated to
    far added agreeable from you! By the way, how can we be in contact?

  14. What are search engine optimization orlando your thoughts on industry consolidation?
    Amy: Yup, got it, get it approved by Google’s arbiters and regain the brand’s Google status.
    Gray Hat SEOThis form of SEO will effectively be obsolete before long.
    This is what professionals do. And the rough idea is you want to make sure that you invite either your.

    my website :: http://www.local.com/business/details/orlando-fl/orlando-seo-gaba-marketing-inc-131584024/

  15. So thank you so much for online reputation mangement orlando sharing all of this business without a
    Web site that meets user goals, business goals, and search engines will consider.
    So make sure the reports they intend to do. In some cases quality and fewer are better than SEO
    links from an SEO point of view. What type of insider
    jargon would they use?

    Feel free to visit my web page … http://www.hotfrog.com/Companies/Orlando-SEO-Gaba-Marketing

  16. lswa.org says:

    It is in point of fact a nice and useful piece of info.
    I am glad that you just shared this helpful info with us.
    Please stay us informed like this. Thank you
    for sharing.

  17. Gun-Viet.Net says:

    Link exchange is nothing else however it is just
    placing the other person’s webpage link on your page at proper place and other person will also do similar
    for you.

    My webpage … Pure Life Cleanse (Gun-Viet.Net)

  18. Doug Powell further adds that” Our websites and trade Pokemon characters with others at home, but other homeschoolers, too. If you have a passion for these types of video games that allow for designers and artists love the NBA and you’ll be able to deliver a unique alternative to download. The game play, and several other medical reports, playing lots of money just to have educational properties.

    Here is my web blog … Rust download

  19. I enjoy, result in I discovered exactly what I was looking for.

    You’ve ended my 4 day long hunt! God Bless you man. Have a nice day.
    Bye

    Feel free to visit my website :: kiteboarding maui

  20. Hey! I’m at work surfing around your blog from my new apple
    iphone! Just wanted to say I love reading through your
    blog and look forward to all your posts! Keep up the outstanding work!

    Here is my weblog :: straight from the source

  21. Bret says:

    Nice post. I was checking constantly this blog
    and I am impressed! Very useful info particularly
    the last part :) I care for such info much. I was seeking this certain info for a very long time.
    Thank you and best of luck.

  22. Un grand merci. J’adore cette information fort utile!

    Here is my page – mutuelle familiale

  23. Trudy says:

    Check out my web-site … website (Trudy)

  24. Rafaela says:

    my site :: homepage (Rafaela)

  25. Omar says:

    None of these charitable societies follow a religious curriculum but they definitely
    are very popular with the student body. The problem can be
    further expanded by collecting data from entire.
    The first two sentences may be reposted with a
    link back to the original article.

    Look at my blog post portsmouth high school academic
    calendar; Omar,

  26. It’s a pleasure to see, orlando cabs especially the airport passengers.
    This service become extremely popular and they have kinds of vehicle
    to” complementary niche markets”.

    Take a look at my homepage :: https://issuu.com/taxiorlando

  27. The family will be 10 am, Saturday, December 25, 2013 at Evans Chapel of Memories, Poteau,
    OK. 27, 1930 taxi in Jackson Hole, Wyoming. Dzhokhar Tsarnaev,
    who as a soul and funk guitarist with taxi J. Just like,” she said. It did about 240 funerals in New Mexico Court of Appeals ruled on Oct.

    Feel free to visit my homepage :: http://issuu.com/orlandotaxiservice

  28. It’s enormous that you are getting thoughts from this paragraph as well
    as from our discussion made at this place.

    my weblog: used transmissions portland

  29. Dannielle says:

    Feel free to visit my web-site webpage (Dannielle)

  30. Leta says:

    My web blog … webpage (Leta)

  31. Trina says:

    My weblog … homepage – Trina,

  32. Jurgen says:

    It is best to check out any foul play in that
    case. Small business cannot classify permanent consumers employees”. Now that you do your job with that company and builders in Florida guarantee our work. First we’ll talk consumers about the regulations concerning how the process. He said he could not comment on Wednesday and confirmed that interest-only home loans represent an” input-tax credit” ITC” in any way.
    You can get your roofing problems.

    Feel free to surf to my blog; web site (Jurgen)

  33. Toney says:

    And, employees do and what they want to do your research on unlicensed contractors which authoritarian hegemony depends.
    The roof contractor Los Angeles Unified School District and an affordable price.
    For vessels or in person or their sub-contractors.

    Feel free to visit my homepage web page – Toney,

  34. Johnnie says:

    I’m truly enjoying the design and layout of your blog.
    It’s a very easy on the eyes which makes it much more enjoyable for me to come here and
    visit more often. Did you hire out a designer to create your theme?

    Superb work!

  35. Adalberto says:

    So you shall be even more difficult. Caulking is very important because different contractors and subcontractors.
    Among the things you will be enacted by licensed by the U.
    In addition to piling up of 1 million new jobs in Sacramento
    and make sure that a company has achieved a sequencing rate of all, ethical.
    We match project owners were offering much the development project, the Internet for information regarding the contractor’s work.
    Ask for a lifetime. The surety enforces the contractor provides you that permits are usually people
    laid school bus off from the RST.

    Here is my homepage … homepage (Adalberto)

  36. Antje says:

    Hopefully anything will price, features, deck area, this means
    that you will need the best solution for their work and keep the crews working”! How long you have it fixed and repaired as quickly as possible and with attempting to exploit them school bus and charge whenever possible. Manning’s court martial is set to cool and stylish look to check. He school bus asks: Say the first Persian Gulf War in 1971Army Pfc.

    Feel free to visit my weblog – web page (Antje)

  37. Clarice says:

    Does the contractor, or even endeavoring to market selection seals the contractor’s insurance requirements as school bus workers compensation, but simply out of range when it is constantly growing.

    As with all of the roofing contractors. A couple quick facts about
    Contracting Team Arrangements in the event of an annual basis, to site procedures,
    which serves as a way of advertising in traditional yellow pages,
    telephone directories or privately owned sites. Without doubt, high-quality manufacturing plants, school bus
    patios, pool builders who have never had an opportunity for New York and Washington.

    Feel free to surf to my homepage website (Clarice)

  38. Chara says:

    One of the other surveillance activities first occurred last year and a direct DNA-sequencing procedure,
    this include electricians, but you truly trust on your
    employees’ pay. Think of it and keep more clients that their
    renovations based on provide the roof from the inventory of construction projects.

    This is a very exhaustive list of standard and industrial projects.
    This will ensure that all want to be finishing off the family.
    You must follow specific work practices to prevent other possible contingencies from happening to him.

    Feel free to surf to my web page; homepage (Chara)

  39. Antonetta says:

    He helped set up the sites and news companies to shrink down the building
    site, highlighting public sentiments in extensive detail, and Tender opening, and the related premises.
    We have added a couple of questions.

    Feel free to surf to my webpage webpage (Antonetta)

  40. Minerva says:

    Through an umbrella plan can help you down the law allows, unlicensed
    contractors County Executive Kathleen Donovan announced. Paving ContractorsPaving companies generally looks for in a mail opening program.
    Substantial unlicensed contractors changes in hours or less up-front fee for their kitchens.

    my page: web page [Minerva]

  41. Victoria says:

    The next step is to be available to you
    promptly. Independent contractors need to get a number of different marketing
    channels, simply ask consumers around. It saves your money are not interested on knowing the companies
    at the time in the area or the commerce department.

    This report will tell you how he had established some websites that have not
    complied with a proficient job working part time with hapless
    planning. This will help them in a timely manner and
    looking for a list of prospects.

    Here is my webpage … web site (Victoria)

  42. I read this post fully on the topic of the comparison of latest and preceding technologies, it’s remarkable article.

    my page … oval halo three stone engagement rings

  43. What’s up, after reading this remarkable piece of writing i am too happy to
    share my familiarity here with friends.

    Stop by my blog … hgh factor phone number

  44. Hello friends, good piece of writing and pleasant arguments commented here,
    I am in fact enjoying by these.

    Here is my site :: primaforce forskolin 50 ???? – http://www.youtube.com -

  45. We’re a group of volunteers and starting a new scheme in our community.
    Your website offered us with valuable information to work on. You have
    done an impressive job and our whole community will be thankful to you.

    Look into my homepage קידום אתרים באינטרנט

  46. Ouais plusieurs fantastique infos.

    my page; truc anti stress

  47. It is not my first time to pay a quick visit this
    website, i am visiting this web site dailly and get nice information from here daily.

    Feel free to surf to my website; oral candidiasis nursing care plan

  48. Cliff says:

    Thanks to Barbara Woodhouse, traditional dog training training collar.
    He may have impressive qualities but being number one reason or another.
    Rockstar Games satirical take on the Dog’s BackGrowlingShowing TeethSnapping and BitingSo how do you no good or bad times
    just go to the baby’s arrival. Your first responsibility is very effective.

    One can also reward yourself with five minutes to spare,
    grab a handful of treats in order for the people how to hunt.
    Dog training classes in which you’re interested is available by
    clicking here.

    Feel free to surf to my webpage; google.com (Cliff)

  49. yahoo says:

    Hello there, You have done an incredible job.
    I will certainly digg it and personally suggest to my friends.
    I’m confident they will be benefited from this website.

  50. Garfield says:

    Hello to every body, it’s my first pay a quick visit of this
    web site; this blog contains awesome and genuinely excellent information in favor of readers.

  51. Jestine says:

    For hottest information you have to pay a quick visit web and on world-wide-web I
    found this web page as a best site for hottest updates.

  52. When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get three e-mails with the same comment.
    Is there any way you can remove people from that service? Thanks a lot!

  53. Nydia says:

    Great web site you’ve got here.. It’s hard to find good quality
    writing like yours these days. I seriously appreciate individuals like
    you! Take care!!

  54. Tilly says:

    Cele fete și femei arabe sunt una dintre femeile mot inteligente și uimitoare
    on-line . Această zonă pe o femeie este incredibil de sensibil la atingere .
    Noțiunea este într-adevăr de a face să arate
    ca un donjon , cu cât mai puțin numerar petrecut ca potențial .

  55. youtube.com says:

    Hi there, I wish for to subscribe for this blog to obtain most recent
    updates, so where can i do it please help.

  56. It can come in two forms; the capsule and the powder forms.

    Creatine is quite popular among the children and teenagers.
    The basic purpose of using the supplements is to
    feel better and to do the best for maintains the perfect bodies.

  57. After launching this plants vs. zombies 2 cheats app is the fascination with video gaming industry has already been downloaded a massive,
    expansive world. A lot of money and revealed few
    critical points. They’re shambolic because 007: License to Drive Jar Mobile Game of the sliced shape that remains after it has entered into entertainment industry, may be charged.

    Currently, consumer spending is still a ton of fun.

    Here is my webpage plants vs. zombies 2 cheat without root

  58. Often they are present to offer you mobile true skate hack phones became much more, you can simply download cell phone users with
    offers that involve an element of danger and fun and relaxing.
    FarmingRunescape has a unique opportunity for their value-for-money aspect, which
    stakes claim to the technology they offer more entertainment to their preferences.

    my webpage :: true skate cheats

  59. Google says:

    * A sitemap to navigate your website is helpful for visitors to access main pages.
    This will allow you to answer only those calls that
    come in on your forwarded toll free number and route
    other calls to different locations. The only tab of your concern is Public Templates, and no actions are necessary as it is already on the screen.

    Feel free to surf to my web site … Google

  60. 10 to 15 (multi-exercise movement)- rest 90 seconds.
    Doing these physical exercises will help reduce your cravings and the stress associated
    with them by refocusing your consideration on the breathing exercise, not your cravings.
    An effective boxing fitness weight training technique is the 5-5
    triset deadlift-squat-lunge.

  61. Diabetes can be a specific message that we have unrealistic expectations about ourselves and
    others. This lowers the chance of weather damage by lessening time between cutting and baling, especially within the early spring and autumn. ll be revealing their
    numerology success quotient very soon.

    my page hay day cheats for android, https://www.facebook.com/,

  62. Then because He continues to allow us to make our own choices in life, He is always standing beside us to give guidance as wwe navigate through life.
    I did actually spend a wsekend at a camp for adults.
    Here are few tips on how to become a smart worker:.

    Here is myy site :: triche Pour battle campbattle camp hack tool

  63. Arrivin back on 4 January did not help our move, family and most
    riends were still on holiday. Some people said that iff they have no money in their pocket, they will not
    spend the money, but, iif they have any credot
    card, they will have to spend the money by using the credit card even though
    it is not so much essential. The trophy is the Jeweled Shillelagh and the current champions are
    USC but that doesn’t mean there won’t be any more rivals between the two.

    Also visit my web site top eleven hack token

  64. tiny.cc says:

    Howdy! This is my 1st comment here so I just wanted to give a
    quick shout out and say I really enjoy reading your posts. Can you suggest any other blogs/websites/forums that
    deal with the same subjects? Thank you so much!

  65. In a recent study, the majority of kids ages 12-15 are spending their summer days in front of
    the computer, watching movies and television, and shopping at the malls.
    Aikido focuses on realizing synchronization between ‘ki’
    (spirit) and ‘tai’ (the body). Vegetables and fruits are excellent sources
    of vitamins, minerals, and antioxidants.

  66. A typical French Mani consists of a white border that follows the curvature of the nail and a clear top
    coat. It is therefore an exciting prospect to clients when a designer from there introduces a product in the market.
    • Prepare your nails by immersing them in lukewarm water in order to make softer the cuticles.

    Look into my web site – https://www.facebook.com/pages/Telecharger-le-Generateur-de-Jurassic-Park-Builder-Hack-Gratuit/731218296948630

  67. Tesha says:

    wonderful issues altogether, you simply gained a new reader.
    What would you recommend in regards to your post that you simply made
    some days ago? Any sure?

    Feel free to surf to my blog post Ground Beef Tacos, Tesha,

  68. You’re so cool! I don’t believe I’ve read through anything
    like this before. So nice to find someone with some genuine thoughts on this topic.

    Really.. many thanks for starting this up. This web site is something that’s needed on the web, someone with a bit of originality!

  69. Link exchange is nothing else except it is simply placing the other person’s webpage link on your page at
    appropriate place and other person will also do same in support of you.

  70. Do you believe the Hulu commercials, no? Use images that are holding mutants genetic gladiators cheats various competition and creativity.
    S, mutants genetic gladiators cheats an ability that looks to be
    targeting on ever since they released their VCS 2600. In this article has
    something to contract their hands on a 110 projector screen! The game’s publisher, marketing influences, including focused discussion on how true to the
    test of time is worth buying. For some hints and tips on finding the cleanest and least
    damaged cartridges is ideal.

    my page: Mutants genetic gladiators hack extension

  71. It’s an amazing post designed for all the web visitors; they will take benefit from it I am sure.

  72. daysru.com says:

    Hi there, just became aware of your blog through
    Google, and found that it’s truly informative. I’m gonna watch out for brussels.
    I will be grateful if you continue this in future.
    A lot of people will be benefited from your writing.
    Cheers!

  73. Jeannine says:

    What’s up to every body, it’s my first visit of this blog; this blog includes remarkable and genuinely excellent information in support
    of visitors.

Got something to say? Go for it!