最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Backbone model is undefined? - Stack Overflow

programmeradmin0浏览0评论

I can't understand why this.model would be defined in view.intialize() when I run this.model.fetch() on it but not in view.render().

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;

});

I can't understand why this.model would be defined in view.intialize() when I run this.model.fetch() on it but not in view.render().

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;

});
Share Improve this question edited Jan 10, 2012 at 16:46 djmccormick asked Jan 10, 2012 at 16:35 djmccormickdjmccormick 4634 silver badges11 bronze badges 1
  • 1 Is this getting de-referenced when success is being called? Maybe you need to bind it. – JaredMcAteer Commented Jan 10, 2012 at 16:46
Add a ment  | 

1 Answer 1

Reset to default 8

It is because the this is being bound differently because render is being used as a callback, put the following line as the first line in your initialize method to bind this to the current view for the render method:

_.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.

发布评论

评论列表(0)

  1. 暂无评论