Backbone model.change()不会触发

时间:2012-08-28 04:09:26

标签: javascript events backbone.js

我目前正在使用Backbone编写应用程序,出于某种原因,它不会更新视图,只会在某些情况下更新。

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

这是我的路由器:

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;

        }

    });

}

这是应用视图(在^上方引用为“app”):

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 );

        }

    }

});

告诉我你是否需要看一些其他课程/模特/观点。

1 个答案:

答案 0 :(得分:1)

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

在Section-model中,我添加了这个:

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();
相关问题