Backbone.js results of fetch doubling - django

I am trying to use Django and tastypie with backbone.js and mustache. I have set up an example to study those. When using the below code I get results of users doubling as:
-Id User name
-1 yol
-2 dada
-1 yol
-2 dada
--- MY CODE ---
// I think this tastypie adjustment is not related with the problem but i want you to see the //whole code
window.TastypieModel = Backbone.Model.extend({
base_url: function() {
var temp_url = Backbone.Model.prototype.url.call(this);
return (temp_url.charAt(temp_url.length - 1) == '/' ? temp_url : temp_url+'/');
},
url: function() {
return this.base_url();
}
});
window.TastypieCollection = Backbone.Collection.extend({
parse: function(response) {
this.recent_meta = response.meta || {};
return response.objects || response;
}
});
(function($){
// MODELS-COLLECTIOS
//USERS
var User = TastypieModel.extend({
url: USERS_API
});
var Users = TastypieCollection.extend({
model: User,
url:USERS_API
});
//VIEWS
var UsersView = Backbone.View.extend({
render: function(){
// template with ICanHaz.js (ich)
this.el = ich.userRowTpl(this.model.toJSON());
return this;
}
});
//main app
var AppView = Backbone.View.extend({
tagName: 'tbody',
initialize: function() {
this.users = new Users();
this.users.bind('all', this.render, this);
this.users.fetch();
},
render: function () {
// template with ICanHaz.js (ich)
this.users.each(function (user) {
$(this.el).append(new UsersView({model: user}).render().el);
}, this);
return this;
}
});
var app = new AppView();
$('#app').append(app.render().el);
})(jQuery);

I would say you are firing two times the render, because your view is listening to all events, try instead to bind it just to reset and see how it goes:
initialize: function() {
this.users = new Users();
this.users.bind('reset', this.render, this);
this.users.fetch();
},

Related

model returns null on controller

i'm working with a a router and a controller, and i need to complete some operations on the controller, this is my model code
AcornsTest.StockRoute = Ember.Route.extend({
model: function(params) {
"use strict";
var url_params = params.slug.split('|'),
url = AcornsTest.Config.quandl.URL + '/' + url_params[0] + '/' + url_params[1] + '.json',
stockInStore = this.store.getById('stock', url_params[1]),
today = new Date(),
yearAgo = new Date(),
self = this;
yearAgo.setFullYear(today.getFullYear() - 1);
today = today.getFullYear()+'-'+today.getMonth()+'-'+today.getDate();
yearAgo = yearAgo.getFullYear()+'-'+yearAgo.getMonth()+'-'+yearAgo.getDate();
if(stockInStore && stockInStore.get('data').length) {
return stockInStore;
}
return Ember.$.getJSON(url,{ trim_start: yearAgo, trim_end: today, auth_token: AcornsTest.Config.quandl.APIKEY })
.then(function(data) {
if(stockInStore) {
return stockInStore.set('data', data.data);
} else {
return self.store.createRecord('stock', {
id: data.code,
source_code: data.source_code,
code: data.code,
name: data.name,
description: data.description,
display_url: data.display_url,
source_name: data.source_name,
data: data.data,
slug: data.source_code+'|'+data.code
});
}
});
}
});
and this is my controller
AcornsTest.StockController = Ember.ObjectController.extend({
init: function() {
"use strict";
this.send('generateChartInfo');
},
actions: {
generateChartInfo: function() {
"use strict";
console.log(this.model);
console.log(this.get('model'));
}
}
});
from the controller i'm trying to get access to the model to get some information and format it, and send it to the view
but this.model or this.get('model') always returns null, how can i successful get access to the model from the controller? thanks
You are overriding the init method, but its broken, do this:
AcornsTest.StockController = Ember.ObjectController.extend({
init: function() {
"use strict";
this._super();
this.send('generateChartInfo');
});
You need to call the parent method.
See this test case: http://emberjs.jsbin.com/gijon/3/edit?js,console,output
The model is not ready at init time. If anyone has official docs please share.

Delay ember view render till $getJSON isLoaded

The problem with this code is that the render code is entered twice, and the buffer is not where I expect it. Even when I get the buffer, the stuff I push in is not rendered to the screen.
App.FilterView = Ember.View.extend({
init: function() {
var filter = this.get('filter');
this.set('content', App.ViewFilter.find(filter));
this._super();
},
render: function(buffer) {
var content = this.get('content');
if(!this.get('content.isLoaded')) { return; }
var keys = Object.keys(content.data);
keys.forEach(function(item) {
this.renderItem(buffer,content.data[item], item);
}, this);
}.observes('content.isLoaded'),
renderItem: function(buffer, item, key) {
buffer.push('<label for="' + key + '"> ' + item + '</label>');
}
});
And the App.ViewFilter.find()
App.ViewFilter = Ember.Object.extend();
App.ViewFilter.reopenClass({
find: function(o) {
var result = Ember.Object.create({
isLoaded: false,
data: ''
});
$.getJSON("http://localhost:3000/filter/" + o, function(response) {
result.set('data', response);
result.set('isLoaded', true);
});
return result;
}
});
I am getting the data I expect and once isLoaded triggers, everything runs, I am just not getting the HTML in my browser.
As it turns out the answer was close to what I had with using jquery then() on the $getJSON call. If you are new to promises, the documentation is not entirely straight forward. Here is what you need to know. You have to create an object outside the promise - that you will return immediately at the end and inside the promise you will have a function that updates that object once the data is returned. Like this:
App.Filter = Ember.Object.extend();
App.Filter.reopenClass({
find: function(o) {
var result = Ember.Object.create({
isLoaded: false,
data: Ember.Object.create()
});
$.getJSON("http://localhost:3000/filter/" + o).then(function(response) {
var controls = Em.A();
var keys = Ember.keys(response);
keys.forEach(function(key) {
controls.pushObject(App.FilterControl.create({
id: key,
label: response[key].label,
op: response[key].op,
content: response[key].content
})
);
});
result.set('data', controls);
result.set('isLoaded', true);
});
return result;
}
});
Whatever the function inside then(), is the callback routine that will be called once the data is returned. It needs to reference the object you created outside the $getJSON call and returned immediately. Then this works inside the view:
didInsertElement: function() {
if (this.get('content.isLoaded')) {
var model = this.get('content.data');
this.createFormView(model);
}
}.observes('content.isLoaded'),
createFormView: function(data) {
var self = this;
var filterController = App.FilterController.create({ model: data});
var filterView = Ember.View.create({
elementId: 'row-filter',
controller: filterController,
templateName: 'filter-form'
});
self.pushObject(filterView);
},
You can see a full app (and bit more complete/complicated) example here

Building Model object from multiple rest calls

I have a route like following where it builds the data from multiple rest calls.
App.IndexRoute = Ember.Route.extend({
model: function() {
var id = 1; //will get as url param later
var modelData = {ab:{},ef:{}};
return ajaxPromise('https://url1/'+ id +'?order=desc').then(function(data){
modelData.ab = data.items[0];
return ajaxPromise('https://url2/'+ id +'/?order=desc').then(function(data){
modelData.ab.x = data.items;
return modelData;
})
});
}
});
My ajaxPromise function is as follows:
var ajaxPromise = function(url, options){
return Ember.RSVP.Promise(function(resolve, reject) {
var options = options || {
dataType: 'jsonp',
jsonp: 'jsonp'
};
options.success = function(data){
resolve(data);
};
options.error = function(jqXHR, status, error){
reject(arguments);
};
Ember.$.ajax(url, options);
});
};
Now the issue is i know that i can use RSVP.all with promise instances but the data returned from these url has to be set to model object like above.
Also there may be few more rest calls which require data from other rest call. Is there any other way i can handle this promises.
PS: data is required right away for a single route
App.IndexRoute = Ember.Route.extend({
model: function() {
var id = 1; //will get as url param later
return Ember.RSVP.hash({
r1: ajaxPromise('https://url1/'+ id +'?order=desc'),
r2: ajaxPromise('https://url2/'+ id +'/?order=desc')
});
},
setupController:function(controller, model){
model.ab = model.r1.items[0];
model.ab.x = model.r2.items;
this._super(controller, model);
}
);
If you have two that have to run synchronously(second depends on first), you can create your own promise, which eon't resolve until you call resolve.
model: function() {
var promise = new Ember.RSVP.Promise(function(resolve, reject){
var modelData = {ab:{},ef:{}};
ajaxPromise('https://url1/'+ id +'?order=desc').then(function(data){
modelData.ab = data.items[0];
ajaxPromise('https://url2/'+ id +'/?order=desc').then(function(data){
modelData.ab.x = data.items;
resolve(modelData);
})
});
});
return promise;
},

Ember - Cannot set property 'type' of null

I have a big problem with ember. If i navigate to somewhere, i get the error Cannot set property 'type' of null sometimes and the view will not be rendered. The Error is thrown in jQuery, not in Ember.
I have never set something.type in my Application. I dont know what the error could be. An Example of a Route + Controller + View (dont forget, its not happening every time.)
Routing: this.route("channels", {path: "/channels/:only"});
Route:
App.ChannelsRoute = Ember.Route.extend({
model: function(params) {
var controller = this.controllerFor("channels");
controller.set("only", params.only);
if (!controller.get("hasContent")) {
return controller.updateContent();
}
}
});
Controller:
App.ChannelsController = Ember.ArrayController.extend({
sortProperties: ["position"],
sortAscending: true,
hasContent: function() {
return this.get("content").length > 0;
}.property("#each"),
channels_category: function() {
return this.get("only");
}.property("only"),
filteredContent: function() {
var filterType = "group";
var filterID = 1;
switch(this.get("only")) {
case "primary": filterType = "group"; filterID = 1; break;
case "secondary": filterType = "group"; filterID = 2; break;
case "regional": filterType = "group"; filterID = 3; break;
case "hd": filterType = "hd"; filterID = true; break;
default: filterType = "group"; filterID = 1; break;
}
return this.filterProperty(filterType, filterID);
}.property("#each", "only"),
updateContent: function() {
return $.getJSON(getAPIUrl("channels.json")).then(function(data){
var channels = [];
$.each(data.channels, function() {
var channel = App.Channel.create({
id: this.id,
name: this.name,
group: this.group,
hd: this.hd,
position: this.position,
recordable: this.recordable
});
channels.pushObject(channel);
});
return channels;
});
}
});
Its happening in a lot of controllers. I hope somebody knows a solution.
Can you test this variation of your updateContent function? changed the channels var to the controllers model...
updateContent: function() {
return $.getJSON(getAPIUrl("channels.json")).then(function(data){
var channels = this.get('model');
$.each(data.channels, function() {
var channel = App.Channel.create({
id: this.id,
name: this.name,
group: this.group,
hd: this.hd,
position: this.position,
recordable: this.recordable
});
channels.pushObject(channel);
});
});
}
If it's happening in jQuery, it's occurring either in an AJAX call or some DOM manipulation you're doing with jQuery. Your best start will be to have a fiddle with your AJAX calls, and check any Handlebars helpers you're using (especially if you have any input helpers with types declared).

has no method 'toJSON' error in my view

I'm learning backbone.js and I'm building my first multimodule app. I'm getting an error that I've never seen before and I think I know the reason, but I can't see how to fix it. I believe it's because the model isn't actually available to the view yet, but I can't see why.
The error is:
Uncaught TypeError: Object function (){ return parent.apply(this, arguments); } has no method 'toJSON'
This is for line 11 in my view, msg.App.MessageListItemView.
Here's my model:
var msgApp = msgApp || {};
msgApp.Message = Backbone.Model.extend();
Here's my collection:
var msgApp = msgApp || {};
msgApp.MessageCollection = Backbone.Collection.extend({
model: msgApp.Message,
url: MESSAGES_API // Call to REST API with Tastypie
});
Here's my list view:
var msgApp = msgApp || {};
msgApp.MessageListView = Backbone.View.extend({
el: '#gps-app',
initialize: function() {
this.collection = new msgApp.MessageCollection();
this.collection.fetch({reset: true});
this.render();
this.listenTo( this.collection, 'reset', this.render );
},
// render messages by rendering each message in it's collection
render: function() {
this.collection.each(function(item){
this.renderMessage(item);
}, this);
},
// render a message by creating a MessageView and appending the the element it renders to the messages element
renderMessage: function(item) {
var messageView = new msgApp.MessageListItemlView({
model: msgApp.Message
});
this.$el.append(messageView.render().el);
}
});
Here's my item view:
var msgApp = msgApp || {};
msgApp.MessageListItemlView = Backbone.View.extend({
tagName: 'li',
className: 'message-list-item',
template: _.template($('#messageListItem').html()),
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
And here is my router:
var AppRouter = Backbone.Router.extend({
routes: {
'messages/': 'allMessages',
},
allMessages:function() {
this.messageList = new msgApp.MessageCollection();
this.messageListView = new msgApp.MessageListView({model:this.messageList});
console.log('I got to messages!');
},
});
var app_router = new AppRouter;
I'm looking for any and all suggestions. I'm a noob to begin with, and this is my first multimodule app so I'm having a little trouble managing scope I think.
Thanks for you time!
try to change model: msgApp.Message in msgApp.MessageListView like this:
// render a message by creating a MessageView and appending the the element it renders to the messages element
renderMessage: function(item) {
var messageView = new msgApp.MessageListItemlView({
model: item
});
this.$el.append(messageView.render().el);
}
model parameter in views don't expect type of model, but instance of some model. Hope this helps.