public
Created

solving this.model.view with underscore.js

  • Download Gist
1-theproblem.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
var Credentials = Backbone.Model.extend({
// ... code for a validated event here
});
 
var LoginView = Backbone.View.extend({
initialize: function(){
this.loginButton = $("#login");
 
// tight coupling and leaky code...
this.model.view = this;
this.model.bind("validated", this.validated);
},
 
validated: function(valid){
// even more tight coupling between the view and model
// worse yet, the method, even though it's in the view,
// executes within the scope of the view!
 
if (valid){
this.loginButton.removeAttr("disabled");
} else {
this.loginButton.attr("disabled", "true");
}
}
});
2-thereisnospoon.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
$(function(){
 
var SomeModel = Backbone.Model.extend({
raiseIt: function(data){
this.set({data: data});
this.trigger("someEvent");
}
});
 
var SomeView = Backbone.View.extend({
el: "#input",
 
events: { "change #input": "showIt" },
 
initialize: function(){
this.model.bind("someEvent", this.showIt);
$("#input").change(this.showIt);
},
 
showIt: function(){
if (this.model)
alert(this.model.get('data'));
else
alert("there is no model attribute!");
}
});
 
var someModel = new SomeModel();
var someView = new SomeView({model: someModel});
 
// what do you expect the alert boxes to show for these two lines?
// what do you expect it to show when you change the text input field?
someModel.raiseIt("foo");
someView.showIt();
 
});
3-thereisnospoon.html
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13
<html>
<head>
<script src="jquery-1.6.1.min.js"></script>
<script src="underscore-min.js"></script>
<script src="backbone-min.js"></script>
<script src="example.js"></script>
</head>
<body>
<form action="/login" id="login-form">
input: <input type="text" id="input">
</form>
</body>
</html>
4-bindall.js
JavaScript
1 2 3 4 5
initialize: function(){
_.bindAll(this, "showIt");
this.model.bind("someEvent", this.showIt);
$("#input").change(this.showIt);
},
5-fixingtheloginview.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
initialize: function(){
_.bindAll(this, "validated");
this.username = $("#username");
this.password = $("#password");
this.loginButton = $("#login");
this.model.bind("validated", this.validated);
},
 
validated: function(valid){
if (valid){
this.loginButton.removeAttr("disabled");
} else {
this.loginButton.attr("disabled", "true");
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.