javascript - Backbone 模型未定义?

标签 javascript backbone.js

我不明白为什么当我在 this.model 上运行 this.model.fetch() 而不是在 view.render() 中时,它会在 view.intialize() 中定义。

Chrome Developer Tools Screenshot

define([
  'jquery',
  'underscore',
  'backbone',
  'text!templates/example.html'
], function($, _, Backbone, exampleTemplate){

  var exampleView = Backbone.View.extend({
    el: $('body'),
    initialize: function() {
      this.model.set({ _id: this.options.user_id });
      this.model.fetch({
        success: this.render,
        error: function(model, response) {
          console.log('ERROR FETCHING MODEL');
          console.log(model);
          console.log(response);
        }
      });
    },
    render: function() {
      console.log('HELLO FROM RENDER');
      console.log(this.model);
      console.log('GOODBYE FROM RENDER');
    }
  });

  return exampleView;

});

最佳答案

这是因为 this 的绑定(bind)不同,因为 render 被用作回调,将以下行作为 initialize 方法中的第一行来绑定(bind) this 到渲染方法的当前 View :

_.bindAll(this,"render");

Underscore.js bindAll function

Binds a number of methods on the object, specified by methodNames, to be run in the context of that object whenever they are invoked. Very handy for binding functions that are going to be used as event handlers, which would otherwise be invoked with a fairly useless this.

关于javascript - Backbone 模型未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8806835/

相关文章:

javascript - jquery 错误 n 无效的选择器

javascript - 处理从 javascript 对象获取的数据

php - Facebook Like 按钮 - 如何获取 'liked' 某事的好友数量

javascript - EasySlider1.7 - 如何让第二个 slider 上的箭头起作用?

javascript - 将整数拆分为随机数之和

javascript - Backbone 多事件

javascript - Backbone.js Restful json API 设计

javascript - 在 Marionette 中使用变量作为区域名称

javascript - deferred.fail()后如何继续执行JS

iOS应用程序基本路径