Backbone View事件未触发

ped*_*ofs 19 javascript javascript-events backbone.js

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

简单事件不会运行,但警报('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');
  }
});
Run Code Online (Sandbox Code Playgroud)

和我的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' %>.
Run Code Online (Sandbox Code Playgroud)

产生这个:

<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>
Run Code Online (Sandbox Code Playgroud)

Elf*_*erg 57

骨干视图发生在元素的上下文中.为了使此代码有效,您必须在构造时将该元素分配给View,如下所示:

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

...
Run Code Online (Sandbox Code Playgroud)

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

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

  • 仅供参考:在视图的初始化函数中声明$ el也可以. (2认同)
  • 读者可能很困惑:如今,这不是必要的.如果你没有指定`el`,那么就会为你创建一个`div`,并且所有事件都与之相关. (2认同)