I’m having a hard time figuring out why this is not working. I have two models in Backbone that I want to decouple by moving to an evented setup. It’s easier to just show you:
var Session = Backbone.Model.extend({
url: '/some/url/session.js',
initialize: function(credentials) {
if (this.isValid() == true) {
this.trigger("start");
}
},
validate: function() {
if (this.get("user") != "user" || this.get("password") != "pass") {
this.trigger("end");
return "Invalid credentials.";
}
}
});
var MainModel = Backbone.Model.extend({
url: '/some/url/config.js',
initialize: function(credentials) {
this.session = new Session(credentials);
this.session.on("start", this.start());
this.session.on("end", this.end());
},
end: function() {
console.debug("session ended");
},
start: function() {
console.debug("session started");
}
});
new MainModel({
"user":"user",
"password": "pass"
});
The problem I’m seeing is that both MainModel.start() and MainModel.end() are being triggered all the time immediately after instantiation. I don’t know if I’m adding the listeners correctly.
Any ideas?
Thanks!
@fguillen is correct, you need to bind the function
this.startand not the result of the function call.Additionally, the order of your bindings is also incorrect. You are validating the user in
Session.intialize, but at this point, the bindings are not yet created. I would suggest to add a separatelogin()function, which is called after you bind your events:Working code here: http://jsfiddle.net/mbuchetics/Ujh72/3/