【问题标题】:Retrieve a Backbone Model from a Clicked Subview and Create a New View with it从单击的子视图中检索主干模型并使用它创建新视图
【发布时间】:2013-09-28 06:30:56
【问题描述】:

假设我已经构建了一个 MainView(一个列表),它使用四个 Backbone 模型填充了一个集合。然后,对于集合中的每个模型,我根据每个模型中的数据呈现一个 SubView(一个列表项)。忽略这种嵌套视图结构是否最佳,我将如何在每个子视图(列表项)上创建一个单击事件,以启动引用用于创建它的模型的新视图?

我在下面的代码中粗略地(在某种程度上)做了我想做的事情:

var MainView = Backbone.View.extend({

initialize: function(){
            this.render();
    //fetch data into a collection
    this.collection.fetch().then(function(){
                this.subRender();
            });
    //view now has a list with four list items based on four models
},

events: {
    "click li": 'newView'
},

newView: function(){
    //retrieve the model from the clicked li
            //close the current view, then
    var newView = new NewView({model});
}

render: function(){
    //create an unordered list element
    this.$el.html('<ul id="list"></ul>');
},

subRender: function(){
    //for each model in the collection create a new subview
    var subView = new SubView({model: model}); // x 4 times

}

});

var SubView = Backbone.View.extend({

el: '#list',

render: function(){
    //create an <li> with the passed-in model
    //append it to the list
},
});

编辑:LosTechies 有一个帖子处理这个我终于找到了......

【问题讨论】:

    标签: backbone.js backbone-views backbone-events backbone-model


    【解决方案1】:

    我认为你可以只设置一个点击事件,但使用 stopImmediatePropagation();

    var SubView = Backbone.View.extend({
        el: '#list',
        events: {
            "click": 'doHandler'
        },
        doHandler: function(event) {
            event.stopImmediatePropagation(); // need this to stop other click handlers and the event bubbling up to ancestor elements
            // do stuff 
        },
        render: function(){
            //create an <li> with the passed-in model
            //append it to the list
        },
    });
    

    【讨论】:

    • 或者放弃父视图中的"click li": 'newView',让SubView处理newView的东西。
    • 我真正关心的是如何获得对单击的子视图的引用。现在单击子视图中的任何
    • 和 console.logging “this”(带有单击事件和附加在子视图中的 e.stopImmediatePropagation())返回第一个子视图,而不是相应的子视图。使用 e.stopPropagation() 执行相同的操作会为每个
    • (如 view1、view2、view3 等)返回一个“this”。那么 - 我将如何通过点击第二个
    • 来返回“view2”?
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签