bluedevil2k bluedevil2k - 24 days ago 5
Javascript Question

Backbone Javascript - Function not Found?

I keep getting a "filterMessages is not a function" error. Here's the Backbone View class - no idea why it can't find the function.

Here's the error in Firebug
filterMessages is not defined
Line 152 (filterMessages("all").each(function(message) {

MessageListView = Backbone.View.extend({

defaults : {
filterString : "all"
},

initialize : function() {

this.collection.on("add", function(model) {
var view = new MessageView({model: model});
$("div.cameras").prepend(view.render().el);
});

this.collection.on("remove", function(model) {
var ID = model.id;
$("#message-" + ID).parent("div.message").remove();
});

this.collection.on("reset", function(models) {
$("div.cameras").empty();
filterMessages("all").each(function(message) {
var view = new MessageView({model: message});
$("div.cameras").prepend(view.render().el);
});

});

},

setFilter : function(filterString) {
this.filterString = filterString;
this.collection.reset(this.collection);
},

filterMessages : function(filterString) {
return this.collection.filter(function(model){

if (filterString == "all")
{
return true;
}
else if (filterString == "active")
{
return model.get("ignore") == "0";
}
else if (filterString == "ignore")
{
return model.get("ignore") == "1";
}
else if (filterString == "flag")
{
return model.get("flag") == true;
}

});
}

});

rjz rjz
Answer

You will want to call it within the context of the view:

initialize : function() {

    var self = this;

    // code here

    this.collection.on("reset", function(models) {
        $("div.cameras").empty();
        self.filterMessages("all").each(function(message) {
            var view = new MessageView({model: message});
            $("div.cameras").prepend(view.render().el);
        });
    });
}