【问题标题】:get data from server Backbone.js application从服务器 Backbone.js 应用程序获取数据
【发布时间】:2013-08-25 18:31:29
【问题描述】:

更新:我正在用 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();
        },

)}

最新更新

router.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 

更新 答案是我想从 ScheduleView.js 中返回一个值

Backbone.js is not a constructor error when create instance of view

【问题讨论】:

标签: javascript backbone.js


【解决方案1】:

您需要在有问题的视图的集合上监听 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)
    }
});

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

所以当你定义模块时,你可以创建一个新的实例。

// 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 
    }
});   

【讨论】:

  • 可能是 set 而不是 reset,具体取决于 Backbone 版本,因此您也需要收听 add/remove/change
  • @loganfsmyth.. 对,这取决于用户想听的事件。
  • @Sushanth-- 我是一个新的backbone.js 用户,所以我有点困惑,所以请你给我一个完整的三个文件的视图以及放置网址的位置
  • 当然.. "http://localhost:8888/client/i/schedule" 的响应到底是什么.. 它是一个对象数组还是一个对象.. 因为你已经在模型中定义了它
  • 这是一个对象数组
猜你喜欢
  • 2012-05-16
  • 1970-01-01
  • 2018-05-12
  • 1970-01-01
  • 2022-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多