如何从 Backbone 模型获取 Django 身份验证后端 API 的属性

How to get attributes from a Backbone model fetching Django auth backend API

我在项目中使用 Django 身份验证后端、Django REST 框架 API 和 Backbone。

var User = Backbone.Model.extend({
  urlRoot: host + 'api/users/'
});

// django auth response
var isAuthenticated = {{ request.user.is_authenticated|yesno:"true,false" }};
if (isAuthenticated){
  var userID = {{ request.user.id }}; // django user id
  console.log(userID); // checking value
  var currentUser = new User({id: userID});
  currentUser.fetch();
  var username = currentUser.get('username');
  console.log(currentUser); // checking value

console.log(currentUser)

的结果
attributes: Object
    email: "y****@*****m"
    first_name: ""
    id: 1
    is_staff: true
    last_name: ""
    url: "http://127.0.0.1:8000/api/users/1/"
    username: "yorsant"

如何阅读attributes:Object

一样,fetch是异步的。

您在控制台中看到数据是因为您探索该对象所花费的时间足以完成到 API 的往返行程。

Chrome 开发工具控制台保留对正在记录的对象的引用,然后当用户与其交互时(通过单击折叠对象),对象旁边的一点 !已显示,您可以阅读:

Value below was evaluated just now.

Backbone Model fetch function 提供您可以传递的不同选项,例如 success 回调。

currentUser.fetch({
    success: function() {
        console.log("username:", currentUser.get('username'));
    }
});

了解这一点后,在 Backbone 视图中,您可以使用 Backbone's events 了解属性何时可以使用。

var View = Backbone.View.extend({
    initialize: function() {
        this.listenTo(this.model, 'sync', this.render);
        this.model.fetch();
    },

    // this is called when the model's sync event is fired, so
    // when the model's attributes are ready.
    render: function() {
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    }
});

"sync" (model_or_collection, response, options) — when a model or collection has been successfully synced with the server.