2012-10-10 30 views
1

我必須在html中插入一個硬編碼的簡單菜單,但我不知道應該在哪裏插入它。 我應該直接在路由器中添加html代碼嗎?如何?在主幹中插入靜態菜單

+2

你能否簡單地解釋一下你想要達到的目標?靜態菜單意味着什麼?爲什麼這麼特別讓你如此困惑,在哪裏插入它? –

回答

0

你應該使用一個骨幹視圖,並讓路由器使其:

http://jsfiddle.net/rd13/g3U7j/11/

var MyView = Backbone.View.extend({ 
    el: '.container', 
    template: "<menu><li>Item</li></menu>", 
    render: function() { 
     this.el.innerHTML = this.template; 
     return this; 
    } 
}); 

var r = Backbone.Router.extend({ 
    routes: { 
     '': 'default' 
    }, 
    default: function() { 
     new MyView().render(); 
    }     
}); 

var router = new r(); 
Backbone.history.start();​ 
2

不,你不應該使用一個路由器,你應該做一個Backbone.View對象這就是應該創建HTML並添加它的那種對象。

沒有模板

var view = Backbone.View.extend({ 
    . 
    . other backbone stuff 
    . 

    ,menu: '<div> menu </div>' 

    ,render: function(){ 
     var compiledHTML= $(this.menu); 
     $('selector').append(compiledHTML); 
    } 

}); 

使用模板

使用HTML菜單在您的網頁HTML插入爲使用

型的簡單方法的簡單之路
。 。你的html代碼 。

. 
. end of your html code 
. 

<script type="text/template" id="marker_small_info_template"> 
    <div> xxx </div> 
</script> 

</body> 

,然後在骨幹使用jQuery把它包起來,並在需要的地方添加到您的網頁。

var view = Backbone.View.extend({ 

    ,render: function(){ 
     var compiledHTML= _.template($("#marker_small_info_template").html()); 
     $('selector').append(compiledHTML); 
     return this; 
    } 

}); 

的複雜和花哨的方式做到這一點(require.js +模板)

是要有HTML代碼作爲一個單獨的文件的模板(Underscore.template例如)然後在Backbone.View中使用Require.JS將其「編譯」爲我獲取,並使用JQuery來包裝和添加它。

define([ 
    'text!templates/menuFrenteItem.html' 
], 
function (templateMenuItem) { 

    return Backbone.View.extend({ 
    . 
    . 
    . 
    ,smallInfo: function(variables){ return _.template(templateMenuItem, variables)} 

    ,render: function(){ 
    var compiledHTML = $(this.smallInfo(dataToCompileTemplate)); 
    $('selector').append(compiledHTML); 
    return this; 
    } 

}

我認爲這是學習在JavaScript中使用模板,這個工具添加到您的安全帶的好機會。