【问题标题】:Backbone View events not firing骨干视图事件未触发
【发布时间】:2011-06-18 00:53:02
【问题描述】:

我使用 Rails3 作为我的后端并 Jammit 到资产...现在我试图不压缩甚至打包资产。

简单事件没有运行,但 alert('asd') int inialize 正在按预期工作。

我也已经在其他对象中尝试过其他类型的事件,但没有成功。

我的代码如下:

var InvoiceStock = Backbone.View.extend({
  initialize: function(args) {
    _.bindAll(this, 'find_product', 'product_added');

    this.products = new ProductCollection();

    this.products.bind('add', this.product_added);

    alert('asd');
  },

  events: {
    "keypress #product_finder": "find_product"
  },

  find_product: function(e) {
    alert('teste');
  },

  product_added: function(product) {
    alert('pqp4');
  }
});

还有我的 RUBY HTML:

 <%= text_field 'search', :isbn_or_isbn10_or_publisher_or_authors_or_name_like, :id => 'product_finder' %> ou
 <%= link_to 'criar um produto', '', :id => 'new_product_link' %>.

生成这个:

<label>Adicionar</label>
<input id="product_finder" class="ui-autocomplete-input" type="text" size="30" name="search[isbn_or_isbn10_or_publisher_or_authors_or_name_like]" autocomplete="off" role="textbox" aria-autocomplete="list" aria-haspopup="true">
ou
<a id="new_product_link" href="">criar um produto</a>

【问题讨论】:

    标签: javascript javascript-events backbone.js


    【解决方案1】:

    主干视图发生在元素的上下文中。为了让这段代码正常工作,你必须在构造时将该元素分配给视图,如下所示:

    var InvoiceStock = Backbone.View.extend({
        el: $('#product_finder').parent()
    
    ...
    

    或者将包含产品查找器的特定 DOM 对象分配给 el。作为替代方案,您可以动态生成元素并使用 jQuery 将其附加到您的 DOM。我都用过。

    Backbone 使用 jQuery 委托来指定和上下文化它的事件。如果您没有为整个视图指定父元素,Backbone 不会正确分配事件管理器。

    【讨论】:

    • 仅供参考:在视图的初始化函数中声明 $el 也是可以的。
    • 可能感到困惑的读者:现在,这不是必需的。如果您不指定el,则会为您创建一个div,并且所有事件都与此相关。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多