2

我想构建一个简单的屏幕,其中一侧的项目列表和另一侧的选定项目详细信息。当用户单击其中一项时-其详细信息显示在“详细信息”部分中。“列表”部分中的选定项目也必须用“活动”类装饰。这是我的路由器代码:

var AppRouter = Backbone.Router.extend({

routes:{
    "":"list",
    "users/:id":"userDetails"
},
list:function () {

    this.usersList = new UsersCollection(usersList);/* new UsersCollection()*/
    var self = this;


    //this.userList.fetch({
       // success: function () {
           this.UsersListView =   new UsersListView({ model: this.usersList });
           $('#sidebar').html(this.UsersListView.render().el);
       // }
    //})//end of fetch


},
userDetails:function (id) {

    if(this.usersList){
        //unselect prevously selected
        if(this.user )this.user.set({'selected':false});

        this.user = this.usersList.get(id);

        //select current
        this.user.set({'selected':true});
        //empty refill the items section
        this.UsersListView =   new UsersListView({ model: this.usersList });
        $('#sidebar').empty().html(this.UsersListView.render().el);


        if (this.UserDetailsView) this.UserDetailsView.close();
        this.UserDetailsView = new UserDetailsView({model:this.user});

        $('#content').html(this.UserDetailsView.render().el);
    }
    else{

    }
}
});

到目前为止,我设法通过清空和重新填充项目部分 html 来设置“活动”项目类。有没有办法观察(如在knockoutjs中)'selected'属性,所以一旦它改变 - 改变将在html中可见?

视图代码:

window.UserListItemView = Backbone.View.extend({
    tagName:"li",

    template:_.template($('#tpl-user-list-item').html()),

    render:function (eventName) {
        if(this.model.get('selected')){$(this.el).addClass('active');}
        $(this.el).html(this.template(this.model.toJSON()));

        return this;
    }
});

谢谢转发

4

1 回答 1

3

就是您要查找的内容(尤其是 Events#listenTo 方法)。
所以; 在你看来:

initialize: function() {
  // listen to your model
  this.listenTo(this.model, 'change:selected', this.updateClass);
},
updateClass: function() {
  // something like...
  this.$el.toggleClass('active');
}
于 2013-04-09T08:35:47.090 回答