S
S
Suliman2016-11-27 20:39:35
JavaScript
Suliman, 2016-11-27 20:39:35

Why is the value not displayed in a fairly simple backbone.js code?

Hello.
What am I doing wrong in this code

// App
window.App = {
  Models: {},
  Collections: {},
  Views: {}
}


// User
App.Models.User = Backbone.Model.extend({
  url: 'https://jsonplaceholder.typicode.com/users/1'
});

var User = new App.Models.User();
User.fetch();

console.log( User );
console.log( User.get('name') );

why console.log( User.get('name') ); outputs - undefined.
What is wrong?
Or does .get() only work within the model itself?
UPD: or maybe it would be more correct to write
// App
window.App = {
  Models: {},
  Collections: {},
  Views: {}
}


// User
App.Models.User = Backbone.Model.extend({
  url: 'https://jsonplaceholder.typicode.com/users/1',
  checkAuth: function(){
    this.fetch({
      success: function(mod, res){
        console.log('Успешно');
        console.log(res.name);
      },
      error:function(mod, res){
        console.log('Не успешно');
            }
        });
  }
});

var User = new App.Models.User();
User.checkAuth();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Dudin, 2017-01-27
@outbreak

// User
App.Models.User = Backbone.Model.extend({
  urlRoot: 'https://jsonplaceholder.typicode.com/users/',
  checkAuth: function () {
    var options = {
      success: function (mod, res) {
        console.log('Успешно');
        console.log(res.name);
      },
      error: function (mod, res) {
        console.log('Не успешно');
      }
    }

    this.fetch(options);
  }
});

var userID = 1;

var user = new App.Models.User({
  id: userID
});

user.checkAuth();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question