在 Backbone - 在 CoffeeScript 中触发和侦听不同类的事件
Triggering and Listening to Events across different classes in Backbone - In CoffeeScript
基本上我是Backbone的新手。在我看来,我正在更改集合中名为"limit"的属性。然后我尝试触发一个事件(当属性刚刚更改时),允许我侦听事件并执行其他操作。
但是,当某些内容发生更改时触发我的集合中的事件,并在发生更改时侦听该更改是行不通的。我认为这与视图和集合相互通信有关。任何帮助将不胜感激!谢谢
触发事件的代码(在我的集合中)是:
@trigger("change") #TRIGGER THE EVENT
更改我的集合中的属性(有效)的代码是:
@Properties.attr("limit", "1000") #Change the limit attr to "1000"
侦听更改(不起作用)的代码是:
@Properties.on("change", ->
alert("Attribute has been changed!")
)
完整的代码是:
class PropertyCollection extends Backbone.Collection
model: Property
constructor: ->
super
initialize: ->
@_attr = {}
#Function to change attribute of collection
attr: (prop, value) ->
if value is undefined
@_attr[prop]
else
@_attr[prop] = value
@trigger("change") #TRIGGER THE EVENT
limit: "0" #Attribute - default is set to 0
class HomeView extends Backbone.View
constructor: ->
super
initialize: ->
@Properties = new PropertyCollection
@Properties.attr("limit", "1000") #Change the limit attr to "1000"
#Listen for the change
@Properties.on("change", ->
alert("Attribute has been changed!")
)
template: _.template($('#home').html())
render: ->
$(@.el).html(@template)
在进行更改后注册以侦听该更改
更改属性 ->触发事件 ->无人侦听 ->注册侦听
所以改变这个:
initialize: ->
@Properties = new PropertyCollection
@Properties.attr("limit", "1000") #Change the limit attr to "1000"
#Listen for the change after the firing of the change (why?!!!)
@Properties.on("change", ->
alert("Attribute has been changed!")
)
对此
initialize: ->
@Properties = new PropertyCollection
#Listen for the change BEFORE you make it (yes yes yes!!!)
@Properties.on("change", ->
alert("Attribute has been changed!")
)
@Properties.attr("limit", "1000") #Change the limit attr to "1000"
希望这有帮助!
相关文章:
- 分派点击事件并保留击键修饰符
- 模糊事件的Javascript测试
- keyup事件处理程序更改焦点不适用于快速键入
- 使用 jQuery 的 .on 函数如何获取事件的原始元素
- 如何使Javascript动态html表及其上的事件
- 使用类从一个标记中双击事件
- 如何在未直接触发的情况下停止事件
- 如何在elfinder插件(一个文件管理器插件)上获得上传前事件
- 在 Backbone - 在 CoffeeScript 中触发和侦听不同类的事件
- YUI3-具有相同类的链接的点击事件处理
- 如何使用输入模糊事件更新多个具有相同类名的标签的文本
- JavaScript 将事件添加到相同类名的元素
- j查询如何为具有相同类名的多个元素激活一个事件
- 按键,键控和更改具有相同类名的输入的事件
- jQuery事件,以查找具有相同类$(this)的元素
- 如何停止事件传播到具有相同类的其他元素
- 正在寻找一种在spectrumjs中具有相同类名的两个不同按钮上触发单独事件的方法
- 单击同类的克隆元素上的事件
- 选择与当前事件目标具有相同类名的所有元素
- 如何为具有相同类名的多个按钮添加事件侦听器?