Backbone model.change() not firing



我目前正在使用Backbone编写一个应用程序,由于某些原因,它不会更新视图,但仅在某些情况下更新。

如果我在index.html#/blog/2刷新页面,它会很好地加载页面,一切都很好。但是,如果我刷新index.html#/blog/1的页面,然后将URL更改为index.html#/blog/2并按enter键(NOT refresh),则更改永远不会被触发。

这是我的路由器:

makeChange: function() {
    // Set activePage to the current page_id => /blog/2
    var attributes = {activePage: this.page_id};
    var $this = this;
    // Loop through all sections in the app
    app.sections.some( function( section ) {
        // Check if section has the page
        if( !section.validate( attributes ) )
        {
            // If it has, set the activePage to /blog/2
            section.set( attributes, {silent: true} );
            // Set active section to whatever section-id was matched
            app.set( {activeSect: section.id}, {silent: true} );
            console.log('Calling change!');
            // Calling change on both the app and the section
            app.change();
            section.change();
            console.log('Change complete!');
            return true;
        }
    });
}

这是应用程序视图(在^上方被称为"应用程序"):

var AppView = Backbone.View.extend({
    initialize: function( option ) {
        app.bind( 'change', _.bind( this.changeSect, this ) );
    },
    changeSect: function() {
        var newSect = app.sections.get( app.get('activeSect' ) );
        var newSectView = newSect.view;
        if( !app.hasChanged( 'activeSect' ) )
            newSectView.activate( null, newSect );
        else
        {
            var oldSect = app.sections.get( app.previous( 'activeSect' ) );
            var oldSectView = oldSect.view;
            newSectView.activate( oldSect, newSect );
            oldSectView.deactivate( oldSect, newSect );
        }
    }
});

如果您需要查看其他类/模型/视图,请告诉我。

我解决了它!只有在同一节中的不同页面之间导航(通过更改节中的activePage)时才会发生这种情况,因此应用程序中的activeSect从未更改,因此从未调用changeSect()。现在,即使activeSect在应用程序中是相同的,并且activePage在部分中发生了更改,它也会调用应用程序中的changeSect()。

在Section模型中,我添加了以下内容:

initialize: function() {
    this.pages = new Pages();
    this.bind( 'change', _.bind( this.bindChange, this ) );
},
prepareForceChange: function() {
    this.forceChange = true;
},
bindChange: function() {
    console.log('BINDCHANGE!');
    if( this.forceChange )
    {
        AppView.prototype.forceChange();
        this.forceChange = false;
    }
},

在上面的router.makeChange()中:

section.set( attributes, {silent: true} );
app.set( {activeSect: section.id}, {silent: true} );

我补充道:

var oldSectId = app.get('activeSect');
if( oldSectId == section.id ) section.prepareForceChange();

最新更新