2013-02-09 65 views
1

我有這樣一個觀點:無法訪問模板的DOM元素骨幹查看

var InvoiceForm = Backbone.View.extend({ 
    template: _.template(addform), 
    initialize: function() { 
     this.$("#buyer").val("test"); 
    } 
}); 

我有一個包含買家ID元素的模板addform。這不是設定值。我知道我在這裏做一些愚蠢的事情:)

+0

這是在用戶選擇的輸入框又名你試圖得到當前的輸入? – 2013-02-09 08:43:16

+0

我正在設置其值 – beNerd 2013-02-09 08:46:21

回答

2

視圖中的骨幹模板不會自動呈現。事實上,在Backbone documentation中,有一些例子可以做到這一點。

如果您使用您的視圖模板,它應該在初始化渲染,你可以寫你這樣的代碼:

var InvoiceForm = Backbone.View.extend({ 
    template: _.template(addform), 
    render: function() { 
     this.$el.html(this.template()); 
     return this; 
    }, 
    initialize: function() { 
     this.render(); // Rendering your template in your this.el element 
     this.$("#buyer").val("test"); // Setting the value of #buyer in your template 
    } 
}); 

以後,您可以使用此觀點是這樣的:

var form = new InvoiceForm({ el: $("#wrapper_for_invoiceform") }); 

檢查在這個小提琴中的演示:http://jsfiddle.net/hsn7J/

+0

非常感謝。任何其他方式來完成我想要的? – beNerd 2013-02-09 09:14:21

+0

你想要完成什麼? :D Backbone可能是最具彈性的JS框架。我無法從你的片段中理解你的任務的一般目的。 – drinchev 2013-02-09 09:17:08

+0

對不起。看到我在模板中有一個文本字段。我需要在它上面使用引導程序的typeahead插件。所以需要在初始化函數的文本字段上附加相同的內容。 – beNerd 2013-02-09 09:20:44

1

如果您嘗試在點擊事件上執行此操作 - 要更改爲「測試」值,可以使用以下操作

initialize: function(){ 
      this.model.on('change', this.render, this);   
     }, 

    render: function() { 
      this.$el.html(this.template(this.model.toJSON())); 
      this.input = this.$('#buyer'); 
      return this; 
     }, 

    events: { 
    'click #buyer' : 'editValue', 
    }, 

    editValue: function(){ 
     this.input.val("test"); 
    } 
+0

沒有不點擊事件。需要附加bootstrap鍵入這個元素,因此需要訪問它 – beNerd 2013-02-09 09:59:23