【问题标题】:Backbone-on-rails event aggregatorBackbone-on-rails 事件聚合器
【发布时间】:2013-08-09 05:24:05
【问题描述】:

我已经解耦了想要响应彼此事件的视图。我在 application.js 文件中添加了一个事件聚合器,并在第一个视图中从我的函数中触发了事件。不过,我似乎无法获得第二个视图来响应该事件。我查看了 Derrick Bailey 对事件聚合器的讨论和 documentcloud.github.io 的讨论。我一直无法找到适用于 coffeescript 的语法,我不知道如何翻译我找到的语法。

我想发布活动的第一个视图如下所示:

class Mlp.Views.PoniesIndex extends Backbone.View

  poniesTemplate: JST['ponies/index']

  events:
    'submit #new_pony': 'createPony'
    'click #pony_up': 'ponyUp'

  initialize: ->
    console.log(Mlp.Collections.Settings)
    @collection.on('reset', @render, this)
    @collection.on('add', @appendPony, this)
    @collection.on('change', @render, this)

  ponyUp: (event) ->
    event.preventDefault()
    Mlp.vent.trigger('ponyUp', @collection)
    @collection.ponyDown()
    @collection.ponyUp()

我的事件聚合器在 application.js 文件中:

//= require jquery
//= require jquery_ujs
//= require underscore
//= require backbone
//= require mlp
//= require_tree ../templates
//= require_tree ./models
//= require_tree ./collections
//= require_tree ./views
//= require_tree ./routers
//= require_tree .

Mlp.vent = _.extend({}, Backbone.Events);

当我将它添加到我的 application.js 文件时,我会得到我想要的控制台日志:

Mlp.vent.bind("ponyUp", function(collection){
 console.log("pony up!");
});

但是当我尝试在视图中添加事件绑定器时,我想接收已发布的事件,但我什么也得不到:

class Mlp.Views.SettingsIndex extends Backbone.View

  template: JST['settings/index']

  events:
     'submit #new_setting': 'createSetting'
     'click #change_of_venue': 'randomSetting'

  initialize: ->
    @collection.on('ponyUp', @alterbox, this) 
    @collection.on('reset', @render, this)
    @collection.on('add', @appendSetting, this)
    @collection.on('change', @render, this)

  alertbox: (collection) ->
    event.preventDefault()
    console.log("pony up!")

我尝试了各种不同的语法,但我仍然不确定我应该在初始化中绑定到集合还是在事件声明中绑定。我见过的例子使用下划线的_.bindAll。当我尝试它抛出“无法读取未定义的'绑定'”时,即使我的 application.js 中需要下划线。我确定这是一些我不明白的基本语法。

提前感谢您的帮助!

【问题讨论】:

    标签: backbone.js ruby-on-rails-3.1 coffeescript eventaggregator event-listener


    【解决方案1】:

    您的收藏不会发送 'ponyUp' 事件,您的事件聚合器 (Mlp.vent) 会。当你这样说时:

    Mlp.vent.trigger('ponyUp', @collection)
    

    您要求Mlp.vent@collection 作为参数发送'ponyUp' 事件,您不会从@collection 触发'ponyUp' 事件。这意味着您想收听Mlp.vent 的活动,并且:

    @collection.on('ponyUp', @alterbox, this) 
    

    应该看起来更像这样:

    Mlp.vent.on('ponyUp', @alterbox, this)
    

    或者,您可以通过以下方式手动触发集合上的事件:

    @collection.trigger('ponyUp', @collection)
    

    这两种方法的主要区别在于,使用Mlp.vent 允许任何人监听事件,即使他们手头没有集合,而@collection.trigger 方法要求每个人在之前都有对集合的引用他们可以监听事件。

    【讨论】:

    • 就是那个!这是一个全新的世界
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多