Pregunta

Soy relativamente nuevo en JavaScript y Backbone. Estoy hacking en una aplicación simple de backbone de nivel principiante. Tengo dos vistas: casa y newentry. Desde casa, hago clic en "Nueva entrada" para obtener Newentry. Desde Newentry, hago clic en "Cancelar" para prestar a casa. Por lo tanto, me gustaría alternar entre casa y Newentry haciendo clic en "Cancelar" y "Nueva entrada" respectivamente.

Sin embargo, no funciona. Esto es lo que trato de hacer:

  1. en casa, haga clic en "Nueva entrada". Newentry se hace correctamente.
  2. en NewentRy, haga clic en "Cancelar". Casa se rinde adecuadamente.
  3. en casa, haga clic en "Nueva entrada". Newentry se hace correctamente de nuevo.
  4. en NewentRy, haga clic en "Cancelar". El hogar no representa. El método asociado con el evento de clic no se dispara por segunda vez.

    ¡Estoy extremadamente perplejo! No puedo averiguar por qué. Me gustaría averiguar si un evento diferente está disparando, pero no sé cómo. ¿Alguien sabe lo que debería hacer?

    javascript:

    var Views = {
        Home: Backbone.View.extend({
            template: $('#homeview-template').template(),
            initialize: function() {
                this.entries = new Collections.Entries();
                this.entries.on('all', this.render, this);
                this.entries.fetch();
            },
            render: function() {
                var currDate = getCurrentDate();
                var innerHtml = $.tmpl(this.template, {
                    currDate: currDate
                });
                this.$el.html(innerHtml);
                return this;
            }
        }),
    
        NewEntry: Backbone.View.extend({
            template: $('#newentryview-template').template(),
            events: {
                'click button#cancel-new-entry': 'cancelNewEntry',
                'all': 'logEvents'
            },
            initialize: function() {
                // currently, do nothing
            },
            render: function() {
                var innerHtml = $.tmpl(this.template);
                this.$el.html(innerHtml)
                return this;
            },
            cancelNewEntry: function() {
                console.log("test 1");
                window.router.showHome();
            },
            logEvents: function(evnt) {
                console.log("works");
                console.log("event", evnt);
            }
        })
    };
    
    var Router = Backbone.Router.extend({
        initialize: function(inputs) {
            this.homeView = new Views.Home();
            this.newEntryView = new Views.NewEntry();
            this.el = inputs.el
        },
    
        routes: {
            "": 'showHome',
            "#": 'showHome',
            'new': 'writeNewEntry'
        },
        showHome: function() {
            this.el.empty();
            this.navigate("");
            this.el.append(this.homeView.render().el);
        },
        writeNewEntry: function() {
            this.el.empty();
            this.navigate('new');
            this.el.append(this.newEntryView.render().el);
        }
    });
    

    html:

    
        <script id='homeview-template' type='text/template'>
        <h1 class='title'>My Journal</h1>
        <div id='curr-date-new-entry'>
            <div id='curr-date'>${currDate}</div>
            <div id='new-entry'>
                <a href='#/new'>New Entry</a>
            </div>
        </div>
        </script>
        <script id='newentryview-template' type='text/template'>
        <h1 class='title'>New Entry</h1>
        <input id='new-entry-title' placeholder='New entry title' type='text'/>
        <input id='new-entry-body' placeholder='New entry content' type='text'/>
        <button id='submit-new-entry'>Submit</button>
        <button id='cancel-new-entry'>Cancel</button>
        </script>
        

¿Fue útil?

Solución

Esto probablemente soluciona su problema:

writeNewEntry: function() {
    this.el.empty();
    this.navigate('new');
    this.el.append(this.newEntryView.render().el);
    //fix: http://backbonejs.org/#View-delegateEvents
    this.newEntryView.delegateEvents();
}

Sin embargo, si no está reutilizando las vistas, le recomendaré que instancia de la vista directamente en el método Writannewentry en lugar de inicializar, de esta manera, de esta manera, no tendrá que llamar manualmente delegación:

writeNewEntry: function() {
    this.el.empty();
    this.navigate('new');
    this.newEntryView = new Views.NewEntry();
    this.el.append(this.newEntryView.render().el);
}

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top