Danny
Danny

Reputation: 1003

Triggering and Listening to Events across different classes in Backbone - In CoffeeScript

Basically I'm new to Backbone. I'm changing an attribute in my collection called "limit", from my view. Then I'm trying to trigger an event (when an attribute has just been changed), allowing me to listen for the event and do other actions.

However, triggering an event from my collection when something is altered, and listening for that change when it occurs doesn't work. I assume it's something to do with the view and collection communicating with each other.. Any help would be much appreciated! Thanks

The code to trigger the event, (inside my collection) is:

@trigger("change") #TRIGGER THE EVENT

The code to change the attribute in my collection (which works) is:

@Properties.attr("limit", "1000") #Change the limit attr to "1000"

And the code to listen for the change (which doesn't work) is:

@Properties.on("change", ->
     alert("Attribute has been changed!")
)

And the full code is:

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)

Upvotes: 2

Views: 1370

Answers (1)

jakee
jakee

Reputation: 18566

You register to listen for that change AFTER you make the change

Change attribute -> trigger event -> no-one listening -> register to listen

So change this:

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!")
  )

to this

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"

Hope this helps!

Upvotes: 3

Related Questions