Read Xml And Append In View Using Backbone Js
How to read XML and append in view with Backbone. XML file has been read and successfully appended in view. But i don't know how to approach in Backbone structure (Using its Model
Solution 1:
Don't put the rendering logic into the collection's parse function.
The collection's role is to manage models and syncing with an API. It's the view's responsibility to render.
First, let's simplify the collection parsing. From the Backbone documentation, parse should do the following only:
The function is passed the raw
responseobject, and should return the array of model attributes to be added to the collection.
parse: function(response) {
var $xml = $(response);
// this will return an array of objectsreturn $xml.find('assets').children('asset').map(function() {
var $asset = $(this);
// returns raw "model" attributesreturn {
asseturl: $asset.attr('asseturl'),
width: $asset.attr('width'),
height: $asset.attr('height')
};
}).get();
},
Then, make a simple view for each asset:
varBookView = Backbone.View.extend({
tagName: 'li',
template: _.template('<span class="asset char"><img width="<%= width %>" height="<%= height %>" src="<%= asseturl %>"></span>'),
render: function() {
this.$el.html(this.template(this.model.toJSON()));
returnthis;
}
});
And it's in the list view that the rendering of each assets is handled.
varBookListView = Backbone.View.extend({
initialize: function() {
this.childViews = [];
this.listenTo(this.collection, "sync", this.render);
},
render: function() {
this.$el.empty();
this.collection.each(this.renderBook, this);
returnthis;
},
renderBook: function(model) {
var view = newBookView({ model: model });
this.childViews.push(view);
this.$el.append(view.render().el);
},
});
To use it:
var bks = newBooks(),
view = newBookListView({ el: $('.character-list'), collection: bks });
view.render();
bks.fetch();
Post a Comment for "Read Xml And Append In View Using Backbone Js"