2012-02-17 11 views
37

Si habilito pushState en el enrutador de la red troncal, ¿necesito usar return false en todos los enlaces o la columna vertebral se encarga de esto automáticamente? ¿Hay muestras, tanto la parte html como la parte script?Backbone.js and pushState

Respuesta

67

Este es el patrón utiliza Tim Branyen en su boilerplate:

initializeRouter: function() { 
    Backbone.history.start({ pushState: true }); 
    $(document).on('click', 'a:not([data-bypass])', function (evt) { 

    var href = $(this).attr('href'); 
    var protocol = this.protocol + '//'; 

    if (href.slice(protocol.length) !== protocol) { 
     evt.preventDefault(); 
     app.router.navigate(href, true); 
    } 
    }); 
} 

Usando que, en lugar de hacerlo de forma individual preventDefault en los enlaces, deja que el router los manejan de forma predeterminada y hacer excepciones por tener un atributo data-bypass. En mi experiencia, funciona bien como un patrón. No conozco ningún gran ejemplo, pero probarlo usted mismo no debería ser demasiado difícil. belleza de Backbone radica en su simplicidad;)

+0

Impresionante, funciona genial. ¡Gracias! – Marcus

+4

Solo un aviso: me di cuenta de que IE7 devolvía la URL absoluta en algunos casos en los que esperaba la URL relativa. Para manejar este caso, querrá normalizar el valor de 'href' para que sea una ruta relativa antes de llamar a navegar. – lupefiasco

+1

Simplemente curioso, ¿qué está haciendo (href.slice (protocol.length)! == protocol)? – dezman

9
$(document.body).on('click', 'a', function(e){ 
    e.preventDefault(); 
    Backbone.history.navigate(e.currentTarget.pathname, {trigger: true}); 
}); 
1

match() o startsWith() (ES 6) también puede ser utilizado para el control de protocolo. Si desea admitir urls absolutas por pathname propiedad, consulte las urls base por location.origin.

function(evt) { 
    var target = evt.currentTarget; 
    var href = target.getAttribute('href'); 

    if (!href.match(/^https?:\/\//)) { 
    Backbone.history.navigate(href, true); 
    evt.preventDefault(); 
    } 
    // or 

    var protocol = target.protocol; 

    if (!href.startsWith(protocol)) { 
    // ... 
    } 
    // or 

    // http://stackoverflow.com/a/25495161/531320 
    if (!window.location.origin) { 
    window.location.origin = window.location.protocol 
    + "//" + window.location.hostname 
    + (window.location.port ? ':' + window.location.port: ''); 
    } 

    var absolute_url = target.href; 
    var base_url = location.origin; 
    var pathname = target.pathname; 

    if (absolute_url.startsWith(base_url)) { 
    Backbone.history.navigate(pathname, true); 
    evt.preventDefault(); 
    } 
} 
0

Usted puede prevenir el comportamiento predeterminado de click en <a> etiquetas de HTML. Simplemente agregue el código siguiente dentro de la etiqueta <script />.

<script> 
$(document).on("click", "a", function(e) 
{ 
    e.preventDefault(); 
    var href = $(e.currentTarget).attr('href'); 
    router.navigate(href, true);router 
}); 
</script> 
Cuestiones relacionadas