Skip to content

Instantly share code, notes, and snippets.

@mxriverlynn
Created June 16, 2011 01:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mxriverlynn/1028505 to your computer and use it in GitHub Desktop.
Save mxriverlynn/1028505 to your computer and use it in GitHub Desktop.
solving this.model.view with underscore.js
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");
}
}
});
$(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();
});
<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>
initialize: function(){
_.bindAll(this, "showIt");
this.model.bind("someEvent", this.showIt);
$("#input").change(this.showIt);
},
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");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment