javascript 主干视图事件未触发

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6393174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:29:58  来源:igfitidea点击:

Backbone View events not firing

javascriptjavascript-eventsbackbone.js

提问by pedrofs

I am using Rails3 as my backend and Jammit to asset... Now I am trying to not compress and even package the asstes.

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

The simple event don't get run, but the alert('asd') int inialize is working as expected.

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

I have already tryed other kinds of events in other objects too, but it didn't work.

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

My code as follow:

我的代码如下:

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');
  }
});

and my RUBY HTML:

和我的 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' %>.

which generates this:

产生这个:

<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>

回答by Elf Sternberg

Backbone views happen within the context of an element. In order for this code to work, you must assign that element to the View at construction time like this:

主干视图发生在元素的上下文中。为了使此代码工作,您必须在构建时将该元素分配给 View,如下所示:

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

...

Or assign to el the specific DOM object that contains the product finder. As an alternative, you can generate the element dynamically and use jQuery to attach it to your DOM. I've used both.

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

Backbone uses jQuery delegate to specify and contextualize its events. IF you don't specify the parent element for the entire view, Backbone does not assign the event manager correctly.

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