javascript - 无法在 Marionette 布局中使用 UI 哈希找到元素

标签 javascript jquery backbone.js marionette

我不确定为什么我无法使用我的 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 对象基本上是从 Marionette.Layout 扩展的自定义对象

Marionette 版本:1.8.8

关于为什么我无法使用 this.ui.btnSave 找到按钮元素的任何想法?

提前致谢!

最佳答案

从同事那里得到了一些帮助,问题可能是因为该元素超出了范围。基本上,在 Layout 对象内部,'this' 不包含该元素。我们能够用 '$("#btnSave",this.buttonset.el)' 替换 'this.ui.btnSave' 并且工作正常。 buttonset 是实际包含 html 元素的区域。

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

2015 年 6 月 3 日更新: 我的另一位同事提供了更好的解决方案。基本上,在我的布局中,我使用显示功能来显示我的 View 。它看起来像这样:

 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.el)设置为模板的 html。截至目前,我的布局不知道区域内的任何元素。它只包含一个显示元素的区域。所以我的布局和我所在区域的元素之间存在某种脱节。

与我之前的解决方法相反,正确的解决方案是在末尾添加以下代码行:

this.bindUIElements();

来自 Marionette 注释来源:

This method binds the elements specified in the “ui” hash inside the view’s code with the associated jQuery selectors.

所以最后的代码是这样的:

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 检索我的元素。

关于javascript - 无法在 Marionette 布局中使用 UI 哈希找到元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30514748/

相关文章:

javascript - 带时间的日期选择器 HH :mm:ss

javascript - 引用 "this"上下文之外的模型

javascript - 在angularjs中内联If else

javascript - 使用node.js制作网站

javascript - Angularjs - 在没有引用的情况下注入(inject)工厂

javascript - 忽略取消触摸启动的尝试 : fastclick warning

javascript - 如果元素具有特定的 CSS 值,请执行此操作

jquery - 具有不同边距的 CSS nth Div

javascript - Backbone 帖子 JSON 为空?

javascript - 如何将backbone.sync与jstorage集成?