无法在木偶布局中使用UI散列找到元素

Can't find element using UI hash in Marionette Layout

本文关键字:UI 元素 布局      更新时间:2023-09-26

我不知道为什么我不能得到按钮元素使用我的UI哈希。我的布局是这样的:

Layout: App.Base.Objects.BaseLayout.extend({
   // Rest of the code left out for brevity
   ui: {
      btnSave: "#btnSave"
   },
   events: {
      "click @ui.btnSave": "onSave"
   },
   onInitialize: function () {
        this.listenTo(App.vent, "DisableSaveButton", function(val) {
            this.disableSaveButton(val);
        },this);
   },
   disableSaveButton: function () {
        this.ui.btnSave.prop("disabled",val).toggleClass("ui-state-disabled",val);
   },
   onSave: function () {
        alert("saved!");
   } 
})

在VS2013中,当我的断点击中disableSaveButton方法内的行时,我在Watch窗口中输入$("#btnSave"),我能够获得元素。因为它的长度是1。从这里,我知道按钮被渲染了。但是,如果我在Watch窗口中输入this.ui.btnSave,我将得到一个长度为0的元素。

我的BaseLayout对象基本上是从木偶扩展的自定义对象。布局

木偶版本:1.8.8

知道为什么我不能找到按钮元素使用this.ui.btnSave?

提前感谢!

从同事那里得到了一些帮助,问题可能是因为元素超出了范围。基本上,在布局对象中,'this'不包含元素。我们可以替换这个。ui。btnSave' with '$("#btnSave",this.buttonset.el)',效果很好。Buttonset是实际包含HTML元素的区域。

这似乎是不一致的,因为即使ui哈希没有工作,使用ui哈希的点击事件确实工作。

更新6/3/2015:我的另一位同事提供了一个更好的解决方案。基本上,在我的布局中,我使用一个显示函数来显示我的视图。它看起来像这样:

 Layout: App.Base.Objects.BaseLayout.extend({
      // Rest of the code left out for brevity
      display: function() {
           $(this.buttonset.el).html(_.template($("#buttonset-view").html(), {"viewType": viewType}));
      }
 })

基本上,我说的是设置区域的html,也就是this。buttonset。到我模板的html。到目前为止,我的布局不知道区域内的任何元素。它只包含一个显示元素的区域。因此,我的布局和我所在区域的元素之间存在某种脱节。

正确的解决方案,与我之前的解决方案相反,是简单地在末尾添加以下代码行:
this.bindUIElements();

摘自《木偶》注释来源:

该方法将"ui"哈希中指定的元素绑定到

最后的代码是这样的

Layout: App.Base.Objects.BaseLayout.extend({
          // Rest of the code left out for brevity
          display: function() {
               $(this.buttonset.el).html(_.template($("#buttonset-view").html(), {"viewType": viewType}));
               this.bindUIElements();
         }
})

有了这个,我终于能够使用this.ui. btnsave .

检索我的元素了