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

时间:2012-08-16 11:23:43

标签: javascript jquery backbone.js coffeescript backbone-events

基本上我是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)

1 个答案:

答案 0 :(得分:3)

您注册以在进行更改后收听该更改

更改属性 - >触发事件 - >没人听 - >注册听

所以改变这个:

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"

希望这有帮助!