Skip to content

Instantly share code, notes, and snippets.

@stefek99
Created April 16, 2013 07:16
Show Gist options
  • Save stefek99/ccdb3dd2e40e5e656805 to your computer and use it in GitHub Desktop.
Save stefek99/ccdb3dd2e40e5e656805 to your computer and use it in GitHub Desktop.
<!-- https://github.com/kjbekkelund/writings/blob/master/published/understanding-backbone.md#a-views-responsibilities -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>title</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script src="http://underscorejs.org/underscore-min.js" type="text/javascript"></script>
<script src="http://backbonejs.org/backbone-min.js" type="text/javascript"></script>
<script>
var events = _.clone(Backbone.Events);
var Status = Backbone.Model.extend({
url: 'xxx.php'
});
var Statuses = function() {};
Statuses.prototype.add = function(text) {
var status = new Status();
// DOCS: http://documentcloud.github.io/backbone/#Model-save
status.save({text : text}, {
success: function(model, data) {
console.log("success callback");
events.trigger('status:add', data.text);
},
error : function(model, xhr, options) {
console.log("error callback");
console.log(model);
console.log(xhr);
console.log(options);
}
});
};
var NewStatusView = Backbone.View.extend({
initialize: function(options) {
this.statuses = options.statuses;
events.on('status:add', this.clearInput, this);
// $('#new-status form').submit(this.addStatus); // this means different things in the constructor and the addStatus method, as it is jQuery that actually calls the latter when the user submits the form
var add = $.proxy(this.addStatus, this); // creates a function where this is always the same — the context you specify as the second argument
this.$('form').submit(add);
},
addStatus : function(e) {
e.preventDefault();
this.statuses.add(this.$('textarea').val());
},
clearInput : function() {
this.$('textarea').val('');
},
});
var StatusesView = Backbone.View.extend({
initialize: function(options) {
events.on('status:add', this.appendStatus, this);
},
appendStatus: function(text) {
this.$('ul').append('<li>' + text + '</li>');
},
});
$(function(){
var statuses = new Statuses();
new NewStatusView({ el: $('#new-status'), statuses: statuses });
new StatusesView({ el: $('#statuses') });
});
</script>
</head>
<body>
<body>
<div id="new-status">
<h2>New monolog</h2>
<form action="">
<textarea></textarea><br>
<input type="submit" value="Post">
</form>
</div>
<div id="statuses">
<h2>Monologs</h2>
<ul></ul>
</div>
</body>
</html>
<?php
$data = $_POST["text"];
$arr = array('text' => $data);
echo json_encode($arr);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment