Backbone model.get(' key')在.fetch()调用之后未定义,甚至在成功回调内部

时间:2015-10-27 13:43:41

标签: javascript jquery backbone.js

我是Backbone.js的新手,刚刚完成基本教程的运行,以创建一个&#34;用户列表&#34; system(https://www.youtube.com/watch?v=FZSjvWtUxYk),其中所有模板,脚本等都是内联创建的。我让一切都很容易,所以我决定尝试模块化事物,因为我知道这是最好的做法。我遵循本指南的AMD方法(https://cdnjs.com/libraries/backbone.js/tutorials/organizing-backbone-using-modules)并让一切正常,除了一件事 - 在编辑用户时,&#34;当前&#34;数据未加载到表单中。到目前为止,我在SO和其他地方发现的所有问题都已经通过将模板生成代码放在成功中来解决:回调.fetch()调用,但我已经这样做了。< / p>

以下是代码:

(我离开了处理require.js配置的main.js和app.js,路由器init等等。他们似乎工作正常。)

// Filename: router.js
define([
  'jquery',
  'underscore',
  'backbone',
  'views/userList',
  'views/editUser'
], function($, _, Backbone, UserListView, EditUserView){
  var AppRouter = Backbone.Router.extend({
    routes: {
      '': 'home',
      'new': 'editUser',
      'edit/:id': 'editUser'
    }
  });

  var initialize = function(){
    var app_router = new AppRouter;

    app_router.on('route:home', function(){
      var userListView = new UserListView();

      userListView.render();
    });

    app_router.on('route:editUser', function(id) {
      var editUserView = new EditUserView();

      editUserView.render({ id: id });
    });

    Backbone.history.start();
  };

  return {
    initialize: initialize
  };
});

视图/ editUser.js

// Filename: views/editUser
define([
  'jquery',
  'underscore',
  'backbone',
  'models/user',
  'text!/templates/editUser.html'
], function($, _, Backbone, UserModel, rawEditUserTemplate) {
  var userListView = Backbone.View.extend({
    // Element to use for this view
    el: $('.page'),

    // Function to call when this view is rendered
    render: function(options) {
      var that = this;

      // If there is an ID, we are editing
      if ( options.id ) {
        // Create the user, passing the ID
        that.editUser = new UserModel({ id: options.id });

        // Fetch the user data
        that.editUser.fetch({
          // When the fetch is returned
          success: function(userData) {
            // Generate the template and pass the data in
            var editUserTemplate = _.template( rawEditUserTemplate );
            that.$el.html(editUserTemplate({ user: userData }));
          }
        })
      }
      else { // We are creating a new user
        // Generate the template with an empty user
        var editUserTemplate = _.template( rawEditUserTemplate );
        this.$el.html(editUserTemplate({ user: null }));
      }
    },
    events: {
      'submit .edit-user-form': 'saveUser',
      'click .delete': 'deleteUser'
    },
    saveUser: function(e) {
      e.preventDefault();

      // Get the details
      var userDetails = $(e.currentTarget).serializeObject();

      // Create a user model
      var user = new UserModel();

      // Save the user details
      user.save(userDetails, {
        success: function(user) {
          Backbone.history.navigate('', { trigger: true });
        }
      });
    },
    deleteUser: function(e) {
      e.preventDefault();

      // Destroy the user we are editing
      this.editUser.destroy({
        // When the destroy is finished
        success: function() {
          // Back to home
          Backbone.history.navigate('', { trigger: true });
        }
      });
    }
  });

  // Our module now returns our view
  return userListView;
});

模板/ editUser.html

<form class="edit-user-form">
  <legend><%= user ? 'Update' : 'Create' %> User</legend>

  <div class="form-group">
    <label for="firstname">First Name</label>
    <input type="text" class="form-control" name="firstname" id="firstname" value="<%= user ? user.get('firstname') : '' %>" />
  </div>

  <div class="form-group">
    <label for="lastname">Last Name</label>
    <input type="text" class="form-control" name="lastname" id="lastname" value="<%= user ? user.get('lastname') : '' %>" />
  </div>

  <div class="form-group">
    <label for="age">Age</label>
    <input type="text" class="form-control" name="age" id="age" value="<%= user ? user.get('age') : '' %>" />
  </div>

  <hr />

  <button class="btn btn-success" type="submit"><%= user ? 'Update' : 'Create' %></button>

  <% if ( user ) { %>
  <input type="hidden" name="id" id="id" value="<%= user.id %>" />
  <button class="btn btn-danger delete">Delete</button>
  <% }; %>
</form>

使用此代码,无论是否编辑或创建,我都会获得一个空白的编辑表单,而不是&#34;创建&#34; vs&#34;更新&#34;模板中的文本开关工作正常。这意味着实际上正在传递用户对象,并且当我将console.log(用户)添加到模板文件中时,它实际上向我显示用户数据。但是,当我记录user.get(&#39; firstname&#39;)或任何其他属性时,它会记录&#34; undefined&#34;。

1 个答案:

答案 0 :(得分:0)

这个问题出现在我的用户模型中,我上面没有提及,因为我当时并不理解为什么它可能是相关的。

我将其定义为:

var userModel = Backbone.Model.extend({
  url: '/users'
});

应该是:

var userModel = Backbone.Model.extend({
  urlRoot: '/users'
});

错误的选项导致API返回集合而不是模型,因此.get()无法正常工作。