Harry
Harry

Reputation: 13329

Backbone events not firing as expected

I initialise the View:

notifications = new tvr.notifications.Collection
notifications.fetch()
new tvr.notifications.View collection:notifications

Im adding "notifications" to a backbone collection:

notifications =  new tvr.notifications.Collection
notifications.fetch()
notifications.create html:this_notification

notifications.coffee

    class Notifiction extends Backbone.Model
    class Notifictions extends Backbone.Collection
        model = Notifiction
        localStorage: new Backbone.LocalStorage 'tvr.notifications'


    class NotificationView extends Backbone.View
        initialize: ->
            @listenTo @collection, "add", @update

        update: ->
            alert "update"

    namespace 'tvr.notifications', (exports) ->
        exports.Model = Notifiction
        exports.Collection = Notifictions
        exports.View = NotificationView

this events are never called, I can see the objects created in the collection.

I just want to know when A new one is added, or deleted from the collection, so I can update a badge number in the HTML.

Upvotes: 1

Views: 457

Answers (1)

dcarson
dcarson

Reputation: 2853

You are trying to bind the "Add" event to a function call, which is not possible. You need to bind the event to a function reference and Backbone's event mechanism will call the function that is referenced on your behalf. Without using alert, here is an example of the difference (in JavaScript).

Function to invoke

var myFunc = function() {
    alert("happy days");
}

Illegal

notifications.on("add", myFunc());

Legal

notifications.on("add", myFunc);

So you can see in your example you are trying to call the alert function and pass an argument of "happy days" when you bind it using on. This is not allowed.

However if you write a parameter-less function that wraps the code you would like to call such as in the myFunc example above and assign it to a variable or other object, you can bind the event to the function's reference. This should then behave the way you are expecting.

Lastly, you should bind the event using listenTo, not on. This is for reasons already discussed on SO. For further reference read the following:

Difference between ListenTo and on

Backbone js .listenTo vs .on

Upvotes: 1

Related Questions