2013-06-20 96 views
2

我是Backbone JS的新學習者,遇到了問題。主幹JS - 獲取屬性

我在網頁上有一個按鈕。點擊按鈕後,屬性「味精」將於

<script> 
    var m = Backbone.Model.extend({ 
     initialize: function(options){ 
      console.log("A view item is created"); 
     }, 
     default: function(){ 
      return{ 
       msg: "hello world", 
       num: 1000 
      }; 
     } 
    }); 

    var v = Backbone.View.extend({ 
     el: $("body"), 
     events: { 
      "click #b": "outputMsg" 
     }, 
     outputMsg: function(model){ 
      $("#d").append(model.get('msg')); 
     } 
    }); 

    var test = new v; 
</script> 

輸出,但調試器顯示有上$問題(「#d」)。追加(model.get(「味精」)) ;

我該如何解決?謝謝!

回答

1

outputMsg將不會收到您的模型作爲參數。實例化視圖時,需要提供對模型的引用。另外,你沒有實例化任何模型。所以...

var v = Backbone.View.extend({ 
    el: $("body"), 
    events: { 
     "click #b": "outputMsg" 
    }, 
    outputMsg: function(){ 
     this.$("#d").append(this.model.get('msg')); // get the model with this.model 
     // also, use this.$, the scoped version of $: http://backbonejs.org/#View-dollar 
    } 
}); 

var test = new v({model: new m}); // give a reference to a model to your view 
1

@ Loamhoof的答案是正確的。你知道,當你寫

outputMsg: function(model){ 
    $("#d").append(model.get('msg')); 
} 

這裏你model會像e(事件),點擊的事件#b