0

木偶很棒,但有些事情可能会让人有些困惑。在我的初始页面加载中,我在 Marionette.Application 的一个区域中显示了一个 Marionette.Layout。但是由于某种原因,点击事件被委托但实际上并没有响应。如果我导航到另一条路线(删除布局视图)然后返回到路线(重新渲染视图),则事件处于活动状态。如果我使视图连续呈现两次,那么它可以工作。也许我初始化这个系统是错误的。

var     ListView =  Backbone.Marionette.Layout.extend({
    el: "#listView", // exists on DOM already
    events: {
        // this is what is supposed to work
        // as well as events in my subviews
        "click" : function() { console.log("clicked");}
    });


var Router = Backbone.Router.extend({

    initialize: function(options) {
        this.app = options.app;
    },
    start: function(page) {
        console.log("start...");
        // with silent false this causes list() to be called
        // and the view is rendered
        // but the ListView does not get its events delegated
        Backbone.history.start({
            pushState:  false,
            silent:     false
        });

        // only by running loadUrl here
        // do I get the events delegated
        // or by switching between other routes
        // and coming back to 'list'

        // but this is causing a second useless calling
        // of list() re-rendering
        console.log("loadUrl...");
        Backbone.history.loadUrl(page);
        // actually the events are not yet delegated at this point
        // if I pause a debugger here.
        // events only active after the  Application finishes its initializers
    },  
    routes: {
        'list': 'list'
    },
    list: function() {
        var lv = ListView({});
        this.app.focus.show(lv)
    }
});

var app = new Backbone.Marionette.Application();

app.addInitializer(function(options) {
    this.router = new Router({app: this});
    this.router.start();
});

app.addRegions({
    // #focus does exist on the DOM
  focus: "#focus",
});

app.start({});

我期望的另类开始会奏效,但遗憾的是没有

    start: function(page) {
        console.log("start...");
        Backbone.history.start({
            pushState:  false,
            silent:     true // don't trigger the router
        });

        // call the router here via history
        console.log("loadUrl...");
        Backbone.history.loadUrl(page);
        // causes page to be rendered correctly 
        // but events are not delegated
    },  

我已经用调试器逐步完成了这一切,但仍然看不到 loadUrl 的神奇效果是什么使它工作。

我也尝试过将布局重新插入该区域:

app.focus.show(app.focus.currentView)

也许有一种不同的方式来构建它,根本不会遇到这个问题。

4

2 回答 2

0

在 onRender 部分添加

this.delegateEvents();

当 Marionette 关闭视图时,它也会取消绑定事件。事件仅在视图初始化时被委托。当您显示以前存储的视图时,您将需要再次调用 delegateEvents 方法。

https://github.com/marionettejs/backbone.marionette/issues/714

于 2013-12-06T02:04:00.900 回答
0

不是100%肯定这是答案,但是...

如果您的元素已经存在于 DOM 上,并且您正在尝试将视图附加到它们,并将该视图附加到区域,请使用区域的attach方法:


list: function() {
  var lv = ListView({});
  this.app.focus.attach(lv)
}

attach方法是专门为您要使用现有 DOM 元素的情况创建的。相反,调用show将替换那里的内容,这可能会导致 jQuery 事件被释放。

于 2012-09-28T03:37:38.883 回答