How to handle the express router method result in

2019-09-04 08:48发布

问题:

I'm new to Backbone.js now i need to handle the express router method result in BackBone.js using ajax i know how to do it with jquery.But without using jquery how to do it with Backbone.I have learned about Backbone router,model,view and collection but still i'm not clear.

app.js

  var express=require('express');
  var app=express();
  app.use(express.bodyParser());
  app.all('*',function(req,res){

      res.writeHead(200, {'Content-Type': 'text/json'});
      res.write(JSON.stringify(result));
      res.end();
   });
   app.listen(8080);

I'm handling all request in express depending upon the request i need to send the header and body of the page.In that 'result' parameter i'm sending the body and header but i don't know how to get that result in Backbone.js.Below code is to handle the ajax response from node js.Is it correct.

client.js

  var MyModel = Backbone.Model.extend();
  var MyCollection = Backbone.Collection.extend({
    url: '/index.html',
    model: MyModel
});
 var coll = new MyCollection();

 coll.fetch({
     error: function (collection, response) {
        console.log('error', response);
    },
    success: function (collection, response) {
        console.log('success', response);
    }
 });

回答1:

Instead of catching all the routes try something like

app.get('/models/',function(req,res){
    res.json({{id: 1, name: 'max'},{id: 2, name: 'bill'}});
});

this is a sample json object of models.

var MyModel = Backbone.Model.extend({});

This is an empty model

var MyCollection = Backbone.Collection.extend({
    url: '/model/',
    model: model
});

A collection that uses our empty model.

var coll = new MyCollection(); 
coll.fetch({success: function () {
    console.log(coll);
}
});

Ignore the error, just focus on the success.

This should work for you. A great tutorial series I found when getting started was http://coenraets.org/blog/2011/12/backbone-js-wine-cellar-tutorial-part-1-getting-started/

Hope this helps