簡體   English   中英

骨干模型未定義?

[英]Backbone model is undefined?

我無法理解為什么this.model會在view.intialize()中定義,當我在它上面運行this.model.fetch()而不是在view.render()中。

Chrome開發者工具截圖

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被綁定不同,因為渲染被用作一個回調,把下面的行作為你的第一行initialize方法綁定this為渲染方法當前視圖:

_.bindAll(this,"render");

Underscore.js bindAll函數

在methodNames指定的對象上綁定許多方法,以便在調用它們時在該對象的上下文中運行。 非常方便用於將用作事件處理程序的綁定函數,否則將使用相當無用的調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM