Backbone Collections - fetch (), successful callback does not work

I am coding in Backbone Js and this is my code:

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();

But the success callback in the collection.fetch () file does not work. He does not record anything!

Here is the JsFiddle: jsfiddle.net/9DjPY/1

Please help me!

+4
source share
2 answers

In case you want to change the implementation of AJAX, Backbone is to extend your Backbone.ajax methods instead of changing jQuery

View should return itself instead of the collection instance. Also, instead of listening to success, you should probably listen to add or reset.

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();

Here is a working example - http://jsfiddle.net/hypernurb/9DjPY/5/ .

Hope this helps.

0

, , :

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!! ");
      }
    });
  }
});
0

Source: https://habr.com/ru/post/1527105/


All Articles