SyntaxScrewer's Blog

October 23, 2012

Filed under: Javascript,Web — geekymaira @ 12:47 pm
Tags: , , , , , ,

Hello,

So I’ve been struggling to get an example going using Backbone Relational and Require.js.
Lack of documentation and simple examples on the web made it really difficult for me to wrap my head around the implementation.
Moreover, Require.js was having scoping issues. Anyway, it works now and I can finally leverage this fantastic Backbone plugin 🙂 .

A few things to keep in mind

1) Make sure you have the updated version of Underscore.js
2) Make sure you have the updated version of Backbone
3) Make sure you have the updated version of Backbone-Relational
4) Test your example on a web server! install xampp, wamp or whateverYouWant! web browser have security restrictions to directly ajax local files.

The example I have below works with 1 Cinema JSON file which has a collection of movie objects inside it.
Here’s the JSON

    {
        "cinemaID":"1",
        "name":"Cinema 1",
        "movies":[
            {
                "movieID":"1",
                "name":"Bag It"
            },
            {
                "movieID":"2",
                "name":"Lost Boy: The Next Chapter"

            },
            {
                "movieID":"3",
                "name":"To Live & Ride in L.A."

            }]
    }

Next comes the MovieModel.js This is a simple extension of the Backbone.RelationalModel

define([],function () {
       var MovieModel = Backbone.RelationalModel.extend({
            idAttribute: 'movieID'
        });
        return MovieModel;
    }
);

Now the CinemaModel.js. This is where the relation with MovieModel is specified. The Backbone Relational documentation
shows that the “relatedModel” attribute should be set to the Model object. The name of this model object is shown to
be in single quotes. I think scoping issues were happening here. The MovieModel for me was being passed by Require.js
using define up top. However, when I had “relatedModel”:”MovieModel”, it didn’t find the Model in scope. So the solution
was to remove the quotes and have it set like “relatedModel”:MovieModel. Since we’re getting a reference to the MovieModel
object using require.js define() anyway.

define(['models/MovieModel','collections/MoviesCollection'],function (MovieModelClass,MoviesCollection) {
        var CinemaModel = Backbone.RelationalModel.extend({
            idAttribute:'cinemaID',
            url:'scripts/data/cinemamodel.json',
            relations: [
                {
                    type: Backbone.HasMany,
                    key: "movies",
//Scoping issue happening here. The documentation for Backbone-Relational has this in quotes!
                    relatedModel:MovieModelClass, 
                    //TODO: Figure out what this attribute does!
                    includeInJSON:Backbone.Model.prototype.movieID,
                    reverseRelation:{
                        key:'inCinema',
                        includeInJSON:Backbone.Model.prototype.cinemaID
                    }
                }
            ]});

        return CinemaModel;
    }
);

Finally, the implementation:

define(['models/CinemaModel'], function (CinemaModel) {

    $(function () {
       init();
    });

    function init() {

        /*Instantiating the CinemaModel*/
       cinemaModel = new CinemaModel();
        cinemaModel.fetch({success:function (collection,response) {
            console.log("Woohooo!: Fetch Cinema Model!");
            console.log ("Relational Model : " + cinemaModel.get('movies').at(0).get('name'));
            console.log ("Reverse Relation : " + cinemaModel.get('movies').at(0).get('inCinema').get('name'));
        },
            error:function (collection, response) {
                console.log("Error: Fetch Cinema Collection!");
            }
        });



    }


});

That’s it!! It works :). Next! I’m going to try and throw collections into the mix and see how I can have a cinemaCollection
with each collection model holding multiple MovieModel objects.

Should be fun 🙂

Cheers!
SyntaxScrewer

Create a free website or blog at WordPress.com.