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.

27 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

Got something to say? Go for it!