简体   繁体   中英

Backbone.js: Updating model attributes inside event does not persist

I have the following in my App.addInitializer

App.addInitializer(function () {
   // Collection Map for dynamic slide-in menus
   var map = {
       'groups': {
           'view': GroupsCollectionView,
           'collection': GroupsCollection,
           'title': "Choose Groups"
       }
   };

   var menuModel = new MenuModel({
           id: 'segments-are-cool',
           mode: 'list'
       }),
       menuView = new MenuView({model: menuModel});

    eventer.on('menu-open', function(type){
        var collectionType = new map[type].collection,
            viewType = new map[type].view({collection: collectionType}),
            title = map[type].title;

        menuView.model.set({type: type, title: title});
        menuView.content.show(viewType);
    });

    App.menu.show(menuView);
});

For some reason when I set the type and title on the model, when my view is displayed, they are not shown to what I set them too (the default value shows up).

I'm a backbone.js newb, so my apologies on my ignorance

As coding_idiot explained in the comments, Backbone (unlike say Angular) does not automatically update View s when their Model s change. While this is slightly less convenient, it gives you much greater control over what happens.

In general most Backbone developers (as coding_idiot suggested) simply invoke View.render after a Model changes. You could even automate this by having the View call this.model.listenTo('change', this.render); inside its initialize method.

Alternatively you could use a library like Epoxy ( http://epoxyjs.org/ ) to further automate your data binding, but personally I wouldn't recommend it just because I think there's a lot of value to having exact control over when and what you re-render.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM