从服务器主干.js应用程序获取数据

get data from server Backbone.js application

本文关键字:应用程序 获取 数据 js 服务器      更新时间:2023-09-26

更新:我正在用Sushanth的答案更新问题,--,我遇到了一些麻烦,阻止代码成功运行[下面问题中我代码的最新更新在此引用"最新更新"及其下面的问题之后]

我正在开发一个 Backbone.js 应用程序,但我无法从服务器获取数据。

http://localhost:8888/client/i/schedule

这个 url 表示所需数据的 json 数组,这里的问题是我如何让视图从集合和模型中读取这些数据

下面有 3 个文件:

第一个是视图

// Filename: views/schedule
define([
'jquery',
'underscore',
'backbone',
'collections/schedule',
'text!templates/schedule.html'
], function($, _, Backbone, scheduleCollection, scheduleTemplate) {
var scheduleView = Backbone.View.extend({
    el: $(".app"),
    initialize: function() {},
    render: function() {             
        console.log('schedule view loaded successfully');
    }
});
return new scheduleView;
});

第二个是收藏

// Filename: collections/schedule
define([
  'jquery',
  'underscore',
  'backbone',
  'models/schedule'
], function($, _, Backbone, ScheduleModel){
  var ScheduleCollection = Backbone.Collection.extend({
    model: ScheduleModel,
    initialize: function(){
        console.log('schedule collections loaded successfully');
    }
  });
  return new ScheduleCollection;
});

第一个是针对模型的

// Filename: models/schedule
define([
  'underscore',
  'backbone',
  'config'
], function(_, Backbone, config) {
var ScheduleModel = Backbone.Model.extend({    
    urlRoot: "http://localhost:8888/client/i/schedule",    
    defaults: {
      feedback: 'N/A'
    },
    initialize: function(){
        console.log('schedule model loaded successfully');
    }
  });
  return ScheduleModel;
});

更新

路由器

    var AppRouter = Backbone.Router.extend({
        routes: {
            // Define some URL routes
            'schedule': 'scheduleRoute',
            // Default
            '*actions': 'defaultRoute'
        },
        scheduleRoute: function() {
            scheduleView.render();
        },
)}

最新更新

路由器.js

define([
    'jquery',    
    'underscore',
    'backbone',
    'app/views/dashboard',
    'app/views/schedule'
], function($, _, Backbone, dashboardView, scheduleView) {
    var AppRouter = Backbone.Router.extend({
        routes: {
            // Define some URL routes
            'schedule': 'scheduleRoute',
            // Default
            '*actions': 'defaultRoute'
        },
        scheduleRoute: function() {
            // Create a new instance of the collection
            // You need to set the url in the collection as well to hit the server
            var schedules = new Schedules();
            // Pass in the collection as the view expects it
            var scheduleView = new ScheduleView({
                collection: schedules
            });
           // No need of calling render here
           // as the render is hooked up to the reset event on collection          
        },
        defaultRoute: function(actions) {            
            // We have no matching route, lets display the home page
            dashboardView.render();
        }
    });
    var initialize = function() {                
        var app_router = new AppRouter;
        Backbone.history.start();
    };
    return {
        initialize: initialize
    };
});

计划视图.js

// Filename: views/schedule
define([
    'jquery',
    'underscore',
    'backbone',
    'app/collections/schedule',
    'text!templates/schedule.html'
], function ($, _, Backbone, scheduleCollection, scheduleTemplate) {
    var scheduleView = Backbone.View.extend({
        collection: scheduleCollection,
        el: $(".app"),
        initialize: function () {
            // Listen to the reset event which would call render
            this.listenTo(this.collection, 'reset', this.render);
            // Fetch the collection that will populate the collection
            // with the response 
            this.collection.fetch();
        },
        render: function () {
            console.log('schedule view loaded successfully');  
            console.log(this.collection);
        }
    });
    return new scheduleView;
});

收藏

// Filename: collections/schedule
define([
    'jquery',
    'underscore',
    'backbone',
    'app/models/schedule'
], function ($, _, Backbone, ScheduleModel) {
    var ScheduleCollection = Backbone.Collection.extend({
        model: ScheduleModel,
        url: "http://sam-client:8888/sam-client/i/schedule",
        initialize: function () {
            console.log('schedule collections loaded successfully');
        }
    });
    return ScheduleCollection;
});

计划模型

// Filename: models/schedule
define([
    'underscore',
    'backbone',
    'app/config'], function (_, Backbone, config) {
    var ScheduleModel = Backbone.Model.extend({
        // If you have any
        //idAttribute : 'someId'
        // You can leave this as is if you set the idAttribute
        // which would be apprnded directly to the url
        urlRoot: "http://sam-client:8888/sam-client/i/schedule",
        defaults: {
            feedback: 'N/A'
        },
        initialize: function () {
            console.log('schedule model loaded successfully');
        }
    });
    return ScheduleModel;
});

问题代码未按预期运行,控制台记录我下面的错误

Uncaught TypeError: Cannot read property '_listenerId' of undefined 

更新答案是我错过了从计划视图返回值.js

主干.js不是创建视图实例时的构造函数错误

您需要侦听集合上的 reset 事件才能获得相关视图。

然后使用 fetch 发送请求。

var scheduleView = Backbone.View.extend({
    el: $(".app"),
    initialize: function() {
       // Listen to the reset event which would call render
       this.listenTo(this.collection, 'reset', this.render);
       // Fetch the collection that will populate the collection
       // with the response 
       this.collection.fetch();
    },
    render: function() {             
        console.log('schedule view loaded successfully');
        console.log(this.collection)
    }
});

为了减少混淆,从模块返回主干视图,模型或集合,而不是新的实例。

因此,在定义模块时,可以创建新实例。

// Filename: views/schedule
define([
    'jquery',
    'underscore',
    'backbone',
    'collections/schedule',
    'text!templates/schedule.html'], function ($, _, Backbone, scheduleCollection, scheduleTemplate) {
    var scheduleView = Backbone.View.extend({
        el: $(".app"),
        initialize: function () {},
        render: function () {
            console.log('schedule view loaded successfully');
        }
    });
    return scheduleView;
    // Remove the returning of new module here
});

在要添加视图作为依赖项的模块中

// Create a new instance of the collection
// You need to set the url in the collection as well to hit the server
var schedules = new Schedules();
// Pass in the collection as the view expects it
var scheduleView = new ScheduleView({
    collection : 
})

更新

// Filename: models/schedule
define([
    'underscore',
    'backbone',
    'config'], function (_, Backbone, config) {
    var ScheduleModel = Backbone.Model.extend({
        // If you have any
        //idAttribute : 'someId'
        // You can leave this as is if you set the idAttribute
        // which would be apprnded directly to the url
        urlRoot: "http://localhost:8888/client/i/schedule",
        defaults: {
            feedback: 'N/A'
        },
        initialize: function () {
            console.log('schedule model loaded successfully');
        }
    });
    return ScheduleModel;
});

收集

// Filename: collections/schedule
define([
    'jquery',
    'underscore',
    'backbone',
    'models/schedule'], function ($, _, Backbone, ScheduleModel) {
    var ScheduleCollection = Backbone.Collection.extend({
        model: ScheduleModel,
        url: "http://localhost:8888/client/i/schedule",
        initialize: function () {
            console.log('schedule collections loaded successfully');
        }
    });
    return ScheduleCollection;
});

视图

// Filename: views/schedule
define([
    'jquery',
    'underscore',
    'backbone',
    'collections/schedule',
    'text!templates/schedule.html'], function ($, _, Backbone, scheduleCollection, scheduleTemplate) {
    var scheduleView = Backbone.View.extend({
        el: $(".app"),
        initialize: function () {
            // Listen to the reset event which would call render
            this.listenTo(this.collection, 'reset', this.render);
            // Fetch the collection that will populate the collection
            // with the response 
            this.collection.fetch();
        },
        render: function () {
            console.log('schedule view loaded successfully');
            console.log(this.collection)
        }
    });
});

在其他模块中,

您将需要要呈现的视图

路由器

var AppRouter = Backbone.Router.extend({
    routes: {
        // Define some URL routes
        'schedule': 'scheduleRoute',
        // Default
        '*actions': 'defaultRoute'
    },
    scheduleRoute: function () {
        // Create a new instance of the collection
        // You need to set the url in the collection as well to hit the server
        var schedules = new Schedules();
        // Pass in the collection as the view expects it
        var scheduleView = new ScheduleView({
            collection: schedules
        });
       // No need of calling render here
       // as the render is hooked up to the reset event on collection 
    }
});