Skip to content

Instantly share code, notes, and snippets.

@dz1984
Last active December 16, 2015 04:59
Show Gist options
  • Save dz1984/5381255 to your computer and use it in GitHub Desktop.
Save dz1984/5381255 to your computer and use it in GitHub Desktop.
Practice the QUnit.js and the Backbone.js framework.
//Define Model class
var BookModel = Backbone.Model.extend();
BookModel.prototype.sync = function(method,model){
console.log(model.cid);
if (method==="create")
model.id = 1;
};
var BookContainer = Backbone.Collection.extend({
model: BookModel
});
// Define View class
var BookView = Backbone.View.extend({
el : "div#message",
template : _.template('Title:<%=title%> Author:<%=author%>'),
initialize : function() {
this.listenTo(this.model, "change", this.render);
},
render : function() {
this.$el.html(this.template(this.model.attributes));
return this;
}
});
test('Book instance Test',function(){
var book = new BookModel({
title: "Test",
author: "Nobody"
});
equal(book.get("title"),"Test","Title is Test.");
equal(book.get("author"),"Nobody","Author is Nobody.");
book.unset("title");
equal(book.has("title"),false,"Title in unset.");
book.clear();
deepEqual(book.attributes,{},"Book is cleared.");
book.set({title:"Boring",author:"Donald"});
equal(book.hasChanged("title"),true,"Title change event is firing.");
equal(book.hasChanged("author"),true,"Author change event is firing.");
book.save();
equal(book.id,1,"Book saved success and the id is 1");
var books = new BookContainer();
books.add(book);
equal(books.length,1,"length of Books container is 1");
var cloneBook = books.get(1);
deepEqual(cloneBook,book,"Get back the book instance is equal to the original book instance.");
});
test('View instance Test',function(){
var book = new BookModel({
title: "Test",
author: "Nobody"
});
var booksView = new BookView({
model: book
});
book.set({title:"ABC"});
equal(booksView.$el.html(),booksView.template(book.attributes),"Content is change.");
});
<!DOCTYPE html>
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<link href="http://code.jquery.com/qunit/qunit-git.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/qunit/qunit-git.js"></script>
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<div id="message">Message</div>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment