Backbone.js : repopulate or recreate the view?

后端 未结 7 1181
灰色年华
灰色年华 2020-11-27 08:49

In my web application, I have a user list in a table on the left, and a user detail pane on the right. When the admin clicks a user in the table, its details should be displ

7条回答
  •  Happy的楠姐
    2020-11-27 09:28

    One alternative is to bind, as opposed to creating a series of new views and then unbinding those views. You'd accomplish this doing something like:

    window.User = Backbone.Model.extend({
    });
    
    window.MyViewModel = Backbone.Model.extend({
    });
    
    window.myView = Backbone.View.extend({
        initialize: function(){
            this.model.on('change', this.alert, this); 
        },
        alert: function(){
            alert("changed"); 
        }
    }); 
    

    You'd set the model of myView to myViewModel, which would be set to a User model. This way, if you set myViewModel to another user (i.e., changing its attributes) then it could trigger a render function in the view with the new attributes.

    One problem is that this breaks the link to the original model. You could get around this by either using a collection object, or by setting the user model as an attribute of the viewmodel. Then, this would be accessible in the view as myview.model.get("model").

提交回复
热议问题