2014-02-26 86 views
1

我在更新我的AppView的$ el HTML內容時遇到了一些麻煩。

初始化我的AppView時,按預期工作。 render()函數在#content div內呈現RoomPickerView的元素,因爲狀態變量初始化爲'pickRoom',因爲它是值。

當在handleCheckRoomResult()函數中再次調用render()時會出現問題。預期的行爲是#content的html被替換爲PlayerCharacterView的元素,但是沒有任何變化,我仍然呈現了以前的HTML內容(房間選擇器)。

如果我在調用render()的末尾記錄AppView的$el.html(),它會顯示正確的HTML,但不知何故,這不會更改實際的DOM。

下面是我的AppView的代碼,我的完整應用程序代碼(目前沒有那麼多)可以找到in this Pastebin

var AppView = Backbone.View.extend({ 
el: '#content', 

state: 'pickRoom', 
roomToken: '', 
character: {}, 

initialize: function() {  
    console.debug('Initializing AppView'); 

    this.characters = new PlayerCharacterCollection(); 

    this.characters.add(new PlayerCharacter({name: 'George', race: 'Elf', klass: 'Blacksmith'})); 
    this.characters.add(new PlayerCharacter({name: 'Amy', race: 'Human', klass: 'Sorceress'})); 

    this.roomPickerView = new RoomPickerView(); 
    this.characterPickerView = new PlayerCharacterPickerView({collection: this.characters}); 

    socket.on('check_room_result', this.handleCheckRoomResult.bind(this)); 

    this.render(); 
}, 

handleCheckRoomResult: function(data) { 
    if (data.result) { 
     this.roomToken = data.token; 
     this.state = 'pickCharacter'; 
     this.render(); 
    } else { 
     console.warn('No room with token ' + data.token + ' exists!'); 
    } 
}, 

render: function() { 
    var htmlString = ''; 

    if (this.state === 'pickRoom') htmlString = this.roomPickerView.render().$el.html(); 
    if (this.state === 'pickCharacter') htmlString = this.characterPickerView.render().$el.html(); 

    console.log(this); 

    console.log(this.$el.html()); 

    // this.$el.html(htmlString); 
    $('#content').html(htmlString); 

    console.log(this.$el.html()); 
} 
}); 

正如你可以看到我已經嘗試過用$('#content').html(htmlString);更換this.$el.html(htmlString);呼籲,希望至少將提供一個臨時的解決方案,但仍然沒有改變在DOM中可以看出。

有沒有人有任何想法是怎麼回事?我走了猜測這裏:(

編輯:

所以我的DOM結構看起來像這樣初始化頁面時:

<body> 
    <div id="wrapper"> 
     <div id="content" class="player"> 

     </div> 
    </div> 
</body> 

我只是檢查我的DOM和#content DIV消失完全和我不知道爲什麼...當我將我的AppView的元素設置爲$('#wrapper')所有工作正常= \任何人都可以解釋這是爲什麼?

此外,感謝您的公司到目前爲止:D

+0

元素是否可用在DOM和ID是唯一的?你能檢查它:'console.log($('[id = content]')。length);' –

+0

你是否檢查過htmlString包含你認爲應該重繪時? –

+0

@KyleNeedham:是的,htmlString完全包含我期望的內容。另外,請參閱我的編輯:)感謝您的評論:) – lunanoko

回答

4

從PastePin中的代碼創建JSFiddle之後,我想通了!

問題出在您的RoomPickerView。您可以設置el以「格」時,你的意思是設置tagName

var RoomPickerView = Backbone.View.extend({ 
    el: 'div'.... 

應該

var RoomPickerView = Backbone.View.extend({ 
    tagName: 'div'... 

此外,讓您的AppView.render()有點清潔小費,這樣做這個:

render: function() { 
    this.$el.html(this.view().render().el); 
}, 

view: function(){ 
    return this.state == 'pickRoom' ? this.roomPickerView : this.characterPickerView 
} 
+0

太棒了!非常感謝你和你的建議:) – lunanoko

相關問題