I notice when I have code like: http://jsfiddle.net/MtULf/1/
window.Todo = Backbone.Model.extend({
defaults: {
"title": ""
},
validate: function() {
if (this.get("title") === "")
return "Title is missing!"
}
});
var todo = new Todo();
console.log("Expects blank: ", todo.get("title"));
todo.set({ title: "A valid title" });
console.log("Expects 'A valid title': ", todo.get("title"));
todo.set("title", "");
console.log("Expects blank: ", todo.get("title"));
All set(...) seems to fail: todo.get("title") always returns empty string
However, if I remove the defaults, I get expected output: http://jsfiddle.net/MtULf/2/
window.Todo = Backbone.Model.extend({
validate: function() {
if (this.get("title") === "")
return "Title is missing!"
}
});
validate isn’t getting the model as it’s context so you need to work with the function attributes, then it works as intended (except validate prevents the title being set to blank)
http://jsfiddle.net/MtULf/3/
no, that’s not true, is it.. validate does get the model as it’s context, but validate runs before the values are set in the model so it always fails when the default is set to “” but succeeds without default because undefined ! === “”.
ok, I think I got it that time..