简体   繁体   中英

consuming RESTful api with backbone

I have a backbone application and a RESTful api. I used the sample created by Coenraets to understand the architecture of a backbone app, but I decided to setup my own structure and just use the data for testing.

I want to know the best way to return data from the RESTful api. I currently have my app folder structure setup with model, collection, view and service folders. I have a node server running with express that handles the backend and is working fine.

What I want to know is what is the best practice for accessing the restful data api? Should I do that in my service class or in my view class? How do I make this work dynamically using the returned data from my restful api: http://localhost:3000/employees

It seems like there are many ways to do this and for now I just want something that works, but eventually I do want to know what is the best way to do it. Ultimately I want to have a CRUD setup. But I'm not sure where that should be setup. Similar to what is detailed here: http://www.codeproject.com/Articles/797899/BackBone-Tutorial-Part-CRUD-Operations-on-Backbone

My files are as follows:

employeecolletion.js

var Backbone = require('backbone');
var Employee = require('../models/employeemodel.js');

module.exports = Backbone.Collection.extend({
    model: Employee,
    url:"http://localhost:3000/employees"
});

employeemodel.js

var Backbone = require('backbone');
var EmployeeCollection = require('../collections/employeecollection.js');

module.exports = Backbone.Model.extend({

    urlRoot:"http://localhost:3000/employees" 

    // initialize:function () {
    //     this.reports = new EmployeeCollection();
    //     //this.reports.url = this.urlRoot + "/" + 1 + "/reports";

    // }

});

employee.js (employee view that binds to my template)

var fs = require('fs');
var base = require('./base.js');
var EmployeeList = require('../collections/employeecollection.js');
var employeeService = require('../services/employeeService.js');
var template = fs.readFileSync('app/templates/employee.mu', { encoding: 'utf8' });


module.exports = base.extend({
  el: '.view',
  template:template,
  collection: employeeService.collection,

  initialize: function () {
    this.viewModel = {
      employee_list: this.collection.toJSON()
      //employee_list: this.collection.fetch() --HERE I EXPERIMENTED WITH FETCHING THE DATA
    };
    this.render();
  }
});

employeeservice.js (file in service folder that would ideally return the collection which I would just bind to my template in they employees view file)

var EmployeeCollection = require('../collections/employeecollection.js');

//if wanting to pass in data manually
var employee_list = [
    {
        id:1,
        firstName:"James",
        lastName:"King",
        fullName:"James King",
        managerId:0,
        managerName:"",
        title:"President and CEO",
        department:"Corporate",
        cellPhone:"617-000-0001",
        officePhone:"781-000-0001",
        email:"jking@fakemail.com",
        city:"Boston, MA",
        pic:"james_king.jpg",
        twitterId:"@fakejking",
        blog:"http://coenraets.org"
    }
];

//HERE I WAS EXPERIMENTING WITH A DIFFERENT SYNTAX TO DO THE FILTERING BY ID
//IN MY SERVICE AND SIMPLY RETURNING THE FINAL DATA I WANT TO MY VIEW CLASS

// var employees = new EmployeeCollection({id: id});

//  employees.fetch({
//      success: function (data) {
//          console.log(data);
//      }
//  });


module.exports = {
  collection: new EmployeeCollection(employee_list)
};

Backbone is meant for RESTful services.

I'll try to explain the basics using some easy to understand terms.

So backbone is based on models and views.

The model is responsible to the data. That means, that the model is the one who fetches the data from the server and stores it. In an interactive application, the model should have a url or urlRoot properties which indicate what is the url of the specific resource this model refers to. For example, if we had a Person resource, and assuming we are consuming a standard RESTfult service, I would expect something similiar to this:

var Person = Backbone.Model.extend({
    url :   'http://localhost:3000/api/Person'
});

That actually lets us create new instances of this model and manipulate it. This url will be used by the model for all CRUD operations related to it.

For example, if we now create a new instance:

var person = new Person();

We now have the following basic CRUD operations:

fetch : this method is executing an async AJAX GET request behind the scenes, and injects the data into the model. Now, after we fetched the data, we can use it by simply calling get : person.get('name'); * assuming there's a name property.

save this method is exectuing an async AJAX POST or PUT request behind the scene. If the model's idAttribute is undefined, it will executed POST , otherwise PUT . The idAttribute is a model property which indicates what is the model's unique id.

A sample usage:

person.set({name : 'Mor'});
person.save();

The abvoe will execute a post request with the name: 'Mor' in the request body. If for example I fetched the model, and already have an idAttribute assigned, calling the same save method will use the PUT request.

destroy this method will execute a DELETE request behind the scene. Sample usage: person.destroy(); .

Obviously I have just shown you the basic usages, there's a lot more options out there.

A collection is simply a list of models so there's not much to explain, you can read more here: http://backbonejs.org/#Collection

A view is all you see. It is the visual part of the application. What Backbone lets us do, is to bind views to models and collections. By that, we can create some dynamic content and visuals.

A basic view would like something like that:

var PersonView = Backbone.View.extend({
  el: '.person',
    initialize: function(){
    this.listenTo(this.model, "change", this.render);
  },
  render: function(){
    this.$el.html("hello :"+this.model.get("name"));
  }
});

As you can see, I used listenTo . It is an event listener that calls render each time the model changes. When I refer to this.model I refer to a model I will pass to the view when I initiate it:

var view = new View({ model : person});

By that, and since I used listenTo , my view is now binded with the person model.

This is basically it. Obviously, there's a lot more to learn and understand, but this pretty much covers the basics.

Please refer to http://backbonejs.org/ and read some more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM