Wednesday, 11 September 2013

Backbone MVC multiple collections used conditionally

Backbone MVC multiple collections used conditionally

I have a plugin that grabs data either from a remote source via ajax or
from local source of data stored in memory. I am having a problem getting
the collection data from the view for local data (collection is empty, see
line 55). The local data is available in the collection as the console.log
on line 42 shows the data. Data from remote and local source are JSON of
the same structure/hierarchy/values.
How can I get the data from local source to be available to the view in
order to render it in the template?
// pluginname
$.fn.pluginname = function(options) {
var defaults = {
source: 'external', // external (fetch data from url) or internal (grab
data from memory)
},
settings = $.extend({}, defaults, options);
// define the model
item = Backbone.Model.extend();
if (settings.source == 'remote'){
// define the collection
items = Backbone.Collection.extend({
model: item,
page: settings.page,
// url to request when fetch() is called
url: function() {
return 'http://www.sample.com/feed.json'
},
parse: function (response) {
return response;
},
// overwrite the sync method to pass over the same origin policy
sync: function (method, model, options) {
var that = this;
var params = _.extend({
type: 'GET',
dataType: 'jsonp',
url: that.url(),
processData: false
}, options);
return $.ajax(params);
}
});
} else if (settings.source == 'local'){
// define the collection
items = Backbone.Collection.extend({
model: item,
sync: function (method, model, options) {
//return JSON.stringify($('body').data('someid'));
return console.log(JSON.stringify($('body').data('someid'))); // logs
data correctly in console
}
});
};
// define the view
itemsView = Backbone.View.extend({
initialize: function () {
_.bindAll(this, 'render');
// create a collection
this.collection = new items;
// fetch the collection and call render() method
var that = this;
console.log(this.collection); // returns empty for json data from
local source
this.collection.fetch({
success: function () {
that.render();
}
});
},
// define template
template: _.template($('#templateid').html()),
// render function
render: function(){
$(this.el).html(this.template({
items: this.collection.toJSON()
}));
},
});
var app = new itemsView({
// define the el where the view will render
el: $('div.content')
});
}; // ends plugin function

No comments:

Post a Comment