2012-01-10 289 views
5

我不明白爲什麼this.model將在view.intialize()中定義,當我運行this.model.fetch(),而不是在view.render()。骨幹模型未定義?

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; 

}); 
+1

成功被調用時'this'被取消引用嗎?也許你需要綁定它。 – JaredMcAteer 2012-01-10 16:46:04

回答

8

這是因爲this被綁定不同,因爲渲染被用作一個回調,把下面的行作爲第一行中的initialize方法綁定this到當前視圖渲染方法:

_.bindAll(this,"render"); 

Underscore.js bindAll function

將對象上的許多方法(methodNames指定)綁定到 ,只要它們被調用,就會在該對象的上下文中運行。非常方便的綁定函數將被用作事件 處理程序,否則將被調用相當無用的。

+0

噢,謝謝! – djmccormick 2012-01-10 16:50:28

+0

@djmccormick不客氣! – 2012-01-10 17:06:22