Last active
December 18, 2015 03:29
-
-
Save ytkhs/5719059 to your computer and use it in GitHub Desktop.
backbone.js sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var SampleModel = Backbone.Model.extend({ | |
}); | |
var SampleCollection = Backbone.Collection.extend({ | |
model : SampleModel, | |
url : '/test/api', | |
parse : function(response) { | |
return response.samples; | |
} | |
}); | |
var SampleView = Backbone.View.extend({ | |
model : SampleModel, | |
tagName: 'li', | |
template: _.template($('#sample-template').html()), | |
render: function() { | |
var template = this.template(this.model.toJSON()); | |
this.$el.html(template); | |
return this; | |
} | |
}); | |
var SampleListView = Backbone.View.extend({ | |
tagName : 'ul', | |
className : 'samples', | |
id : 'sample', | |
initialize: function() { | |
this.collection.on('add', this.addNew, this); | |
}, | |
addNew: function(sample) { | |
var sampleView = new SampleView({model: sample}); | |
this.$el.append(sampleView.render().$el.hide()).children().fadeIn(); | |
}, | |
render: function() { | |
this.collection.each(function(sample) { | |
var sampleView = new SampleView({model: sample}); | |
this.$el.append(sampleView.render().el); | |
}, this); | |
return this; | |
} | |
}); | |
$(function(){ | |
var samples = new SampleCollection(); | |
samples.fetch({ | |
remove : false, | |
data : {hoge:1, fuga:2}, | |
success : function(samples, response) { | |
var sampleListView = new SampleListView({collection: samples}); | |
$('#content').append(sampleListView.render().el); | |
}, | |
error : function(samples, response) { | |
} | |
}); | |
var SampleRouter = Backbone.Router.extend({ | |
routes: { | |
"sample/": "list", | |
"sample/:id": "show" | |
}, | |
list: function() { | |
}, | |
show: function(id) { | |
} | |
}); | |
window.router = new AppRouter(); | |
Backbone.history.start({ pushState: true }); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment