javascript - 在 Backbone 中跨不同类触发和监听事件 - 在 CoffeeScript 中

标签 javascript jquery backbone.js coffeescript backbone-events

基本上我是 Backbone 的新手。从我看来,我正在更改我的集合中名为“限制”的属性。然后我尝试触发一个事件(当属性刚刚更改时),允许我监听该事件并执行其他操作。

但是,当某些内容发生更改时从我的集合中触发事件,并在发生更改时监听该更改是行不通的。我认为这与 View 和集合之间的通信有关。任何帮助将不胜感激!谢谢

触发事件的代码(在我的集合中)是:

@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 - 在 Backbone 中跨不同类触发和监听事件 - 在 CoffeeScript 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11986075/

相关文章:

javascript - 将 onclick 和 onmouseover 组合在同一个函数中

javascript document.getElementById 循环

javascript - 错误: EXDEV: cross-device link not permitted,重命名

javascript - 为什么指令不观察值的变化?

javascript - 使用 Ajax/JQuery 检查用户输入的原始密码

javascript - 当访问者在页面之间移动时,如何使 toggleClass 更改持续存在?

jquery - jquery-mobile 的自定义 CSS。中心可折叠标题

javascript - 用对象填充的外键

dojo - 比较ribs.js和Dojo

javascript - 使用 react.js 在单页应用程序中导航