Backbone Collections - fetch(),成功回调无法正常工作

时间:2014-02-15 17:32:51

标签: javascript backbone.js

我在Backbone Js编码,这是我的代码:

var Router, UserList, Users, router, userList;

    $.ajaxPrefilter(function(options, originalOptions, jqXHR) {
      return options.url = "http://backbonejs-beginner.herokuapp.com" + options.url;
    });

    Users = Backbone.Collection.extend({
      url: '/users'
    });

    UserList = Backbone.View.extend({
      el: '#app',
      render: function() {
        var users;
        users = new Users();
        return users.fetch({
          success: function() {
            return console.log("Please log something!! ");
          }
        });
      }
    });

    userList = new UserList();

    Router = Backbone.Router.extend({
      routes: {
        '': 'home'
      },
      home: function() {
        console.log('Welcome home my friend!!');
        return userList.render();
      }
    });

    router = new Router();

    Backbone.history.start();

但是collection.fetch()中的成功回调是行不通的。它没有记录任何东西!

这是JsFiddle:jsfiddle.net/9DjPY/1

请帮帮我!

2 个答案:

答案 0 :(得分:0)

如果你想改变AJAX实现,Backbone方式是扩展他们的方法Backbone.ajax而不是改变jQuery

View应该返回自己而不是集合实例。 此外,您应该听取添加或重置,而不是听取成功。

var Router, UserList, Users, router, userList,
    oldSync = Backbone.sync;
Backbone.ajax = function(options) {
    var args = Array.prototype.slice.call(arguments, 1);
    options || (options = {});
    if (options.url) {
        options.url = (/^https?/.test(options.url) ? '' : 'http://backbonejs-beginner.herokuapp.com') + options.url;
    }
    return Backbone.$.ajax.apply(Backbone.$, [options].concat(args));
};
Users = Backbone.Collection.extend({
  url: '/users'
});

UserList = Backbone.View.extend({
  el: '#app',
  initialize: function () {
      this.collection = new Users();
  },
  render: function() {
      this.collection.fetch({
          success: function () { console.log('Users', arguments) }
      });
      return this;
  }
});

userList = new UserList();

Router = Backbone.Router.extend({
  routes: {
    '': 'home'
  },
  home: function() {
    console.log('Welcome home my friend!!');
    return userList.render();
  }
});

router = new Router();

Backbone.history.start();

以下是一个工作示例 - http://jsfiddle.net/hypernurb/9DjPY/5/

希望这有帮助。

答案 1 :(得分:0)

您的服务器端可能存在问题,请尝试关注我在fetch中添加错误选项的位置:

UserList = Backbone.View.extend({
  el: '#app',
  render: function() {
    var users;
    users = new Users();
    return users.fetch({
      success: function() {
        return console.log("Please log something!! ");
      },
      error: function(){
        console.log(arguments);
        return console.log("Error log something!! ");
      }
    });
  }
});