So, I think I am in over my head here. I am trying to get fullcalendar to work with backbone and django. I am still learning all of this but I can now make new events and save them via django-tastypie, and they do show up in the calendar, wohoo! However, I can not edit or drag them. Uncaught TypeError: Cannot call method 'isNew' of undefined line 96, is what I get when events are clicked and Uncaught TypeError: Cannot call method 'save' of undefined line 78. I have done my best to figure this out, but no success. Why is this.model.isnew() undefined in render and the same for save? I do not fully understand all of this so I have probably made some stupid mistake somewhere or misunderstood how everything works. I would be grateful if anyone could give me a hint.
I added console.log(fcEvent); to eventClick, and when I inspect it, it says start and end dates are invalid. Does anyone know what that means? If I inspect the same object just after it was added with addOne, the dates are valid. I am also using https://github.com/PaulUithol/backbone-tastypie if that matters.
edit: Tried this to make sure events.fetch() succeeded, this resulted in no events in the calendar whatsoever. Does that mean that events.fetch() never succeeds? I can see "GET /api/event/ HTTP/1.1" 200 6079 in the log.
alternative fetch:
events.fetch({
success: function(){
new EventsView({el: $("#calendar"), collection: events}).render();
}});
Original program:
$(function(){
var Event = Backbone.Model.extend();
var Events = Backbone.Collection.extend({
model: Event,
url: '/api/event/'
});
var EventsView = Backbone.View.extend({
initialize: function(){
_.bindAll(this);
this.collection.bind('reset', this.addAll);
this.collection.bind('add', this.addOne);
this.collection.bind('change', this.change);
this.collection.bind('destroy', this.destroy);
this.eventView = new EventView();
},
render: function() {
this.$el.fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,basicDay'
},
selectable: true,
selectHelper: true,
editable: true,
ignoreTimezone: false,
disableResizing:false,
select: this.select,
defaultView: 'agendaWeek',
eventClick: this.eventClick,
eventDrop: this.eventDropOrResize,
eventResize: this.eventDropOrResize,
events: 'events'
});
},
addAll: function() {
this.$el.fullCalendar('addEventSource', this.collection.toJSON());
},
addOne: function(event) {
this.$el.fullCalendar('renderEvent', event.toJSON(), true);
},
select: function(start, end, allDay) {
var eventView = new EventView();
console.log('select');
eventView.collection = this.collection;
eventView.model = new Event({start: start, end: end, allDay: allDay});
eventView.render();
},
eventClick: function(fcEvent) {
console.log('click');
this.eventView.collection = this.collection;
this.eventView.model = this.collection.at(fcEvent.id);
console.log(fcEvent);
this.eventView.render();
},
change: function(event) {
// Look up the underlying event in the calendar and update its details from the model
var fcEvent = this.$el.fullCalendar('clientEvents', event.get('id'))[0];
fcEvent.title = event.get('title');
fcEvent.color = event.get('color');
console.log('change');
this.$el.fullCalendar('updateEvent', fcEvent);
},
eventDropOrResize: function(fcEvent) {
console.log(fcEvent);
// Lookup the model that has the ID of the event and update its attributes
this.eventView.collection.at(fcEvent.id).save({start: fcEvent.start, end: fcEvent.end});
},
destroy: function(event) {
this.$el.fullCalendar('removeEvents', event.id);
}
});
var EventView = Backbone.View.extend({
el: $('#eventDialog'),
initialize: function() {
_.bindAll(this);
},
render: function() {
var buttons = {'Ok': this.save};
if (!this.model.isNew()) {
_.extend(buttons, {'Delete': this.destroy});
}
_.extend(buttons, {'Cancel': this.close});
this.$el.dialog({
modal: true,
title: (this.model.isNew() ? 'New' : 'Edit') + ' Event',
buttons: buttons,
open: this.open
});
return this;
},
open: function() {
this.$('#title').val(this.model.get('title'));
this.$('#color').val(this.model.get('color'));
},
save: function() {
this.model.set({'title': this.$('#title').val(), 'color': this.$('#color').val(),});
console.log('save');
if (this.model.isNew()) {
this.collection.create(this.model, {success: this.close,wait: true });
} else {
this.model.save({}, {success: this.close});
}
},
close: function() {
this.$el.dialog('close');
},
destroy: function() {
this.model.destroy({success: this.close});
}
});
var events = new Events();
new EventsView({el: $("#calendar"), collection: events}).render();
events.fetch();
});
You can try this. The issue comes down to an undefined Model.
On this line.
select: function(start, end, allDay) {
var eventView = new EventView();
eventView.collection = this.collection;
eventView.model = new Event({start: start, end: end, allDay: allDay});
eventView.render();
},...
Change it to. I have a feeling that your Model is not being instantiated properly.
select: function(start, end, allDay) {
var eventView = new EventView({
collection: this.collection,
model: new Event({start: start, end: end, allDay: allDay})
});
eventView.render();
},
Another issue is, you're instantiating the EventsView and passing in the collection and models before the fetch call.
var events = new Events();
$.when(events.fetch()).then(function() {
// Create the Events view when the Events asynchronous operation completes.
new EventsView({el: $("#calendar"), collection: events}).render();
});
Edit: here's a JS Bin for additional changes.
I got this working except for events not actually disappearing from the calendar, even though they are deleted in the database. I dont know if this is the correct way to do this, probably not, but it worked. Model was undefined in EventView so I had to get the model from the collection and pass it on to EventView.
eventClick: function(fcEvent) {
console.log(fcEvent.id);
this.mymodel = this.collection.where({'id':fcEvent.id})[0];
this.eventView = new EventView({collection: this.collection, model: this.mymodel})
this.eventView.render();
},
change: function(event) {
// Look up the underlying event in the calendar and update its details from the model
var fcEvent = this.$el.fullCalendar('clientEvents', event.get('id'))[0];
fcEvent.title = event.get('title');
fcEvent.color = event.get('color');
console.log('change');
this.$el.fullCalendar('updateEvent', fcEvent);
},
eventDropOrResize: function(fcEvent) {
console.log(fcEvent);
// Lookup the model that has the ID of the event and update its attributes
this.collection.where({'id':fcEvent.id})[0].save({start: fcEvent.start, end: fcEvent.end});
},
Related
I have some acceptance tests that test a component. If I run each test separately, they pass just fine. However, when I run the tests together, they fail because they're retaining the values from the previous tests.
Here is my code:
filter-test.js
module('Integration - Filter', {
beforeEach: function() {
App = startApp();
server = setupPretender();
authenticateSession();
},
afterEach: function() {
Ember.run(App, 'destroy');
server.shutdown();
}
});
test('filters can be saved and selected via the dropdown', function(assert) {
visit('/status');
fillIn('.filter-status', 'Not Completed');
fillIn('.filter-id', '444');
andThen(function() {
assert.ok(find('.status-title').text().includes('2 of 7'), 'the new filter filters the results');
});
});
test('only saved filters can be edited', function(assert) {
visit('/status');
fillIn('.filter-id', 'not an id');
click('.update-filter');
andThen(function() {
assert.equal(find('.alert').text(), 'Not a Saved Filter×');
});
});
test('filter values can be cleared', function(assert) {
visit('/status');
fillIn('.filter-id', '444');
fillIn('.filter-status', 'Completed');
click('.clear-filters');
andThen(function() {
// this fails because `.filter-id` is set to 'not an id':
assert.equal(find('.filter-id').val(), '', 'filter for was reset to its initial value');
// this also fails because `.filter-status` is set to 'Not Completed':
assert.equal(find('.filter-status').val(), 'Everything', 'status dropdown was reset to its initial value');
});
});
ps-filter/component.js
export default Ember.Component.extend({
classNames: ['panel', 'panel-default', 'filter-panel'],
currentFilter: null,
initialValues: null,
didInsertElement: function() {
this.set('initialValues', Ember.copy(this.get('filterValues')));
},
actions: {
saveFilter: function(name) {
var filters = this._getFilterList();
var filterValues = this.get('filterValues');
if (!Ember.isEmpty(name)) {
filters[name] = filterValues;
this.sendAction('updateFilter', filters);
this.set('currentFilter', name);
}
},
updateFilter: function() {
var filterValues = this.get('filterValues');
var currentFilter = this.get('currentFilter')
var filters = this.get('userFilters');
filters[currentFilter] = filterValues;
this.sendAction('updateFilter', filters);
},
clearFilters: function() {
this.set('currentFilter', null);
this.set('filterValues', Ember.copy(this.get('initialValues')));
}
}
});
status/controller.js
export default Ember.ArrayController.extend({
filterValues: {
filterStatus: 'Everything',
filterId: 'id',
},
userFilters: Ember.computed.alias('currentUser.content.preferences.filters')
});
status/template.hbs
<div class="row">
{{ps-filter
filterValues=filterValues
userFilters=userFilters
updateFilter='updateFilter'
}}
</div>
From what I gathered, it seems that it sets the initialValues to the filterValues left over from the previous test. However, I thought that the afterEach was supposed to reset it to its original state. Is there a reason why it doesn't reset it to the values in the controller?
Note that the component works normally when I run it in development.
Ember versions listed in the Ember Inspector:
Ember : 1.11.3
Ember Data : 1.0.0-beta.18
I'm running Ember CLI 0.2.7.
Edit
I don't think this is the issue at all, but here is my pretender setup:
tests/helpers/setup-pretender.js
export default function setupPretender(attrs) {
var users = [
{
id: 1,
name: 'ttest',
preferences: null
}
];
var activities = [
{
id: 36874,
activity_identifier: '18291',
status: 'Complete'
}, {
id: 36873,
activity_identifier: '82012',
status: 'In Progress'
}, {
id: 35847,
activity_identifier: '189190',
status: 'In Progress'
}, {
id: 35858,
activity_identifier: '189076',
status: 'Not Started'
}, {
id: 382901,
activity_identifier: '182730',
status: 'Not Started'
}, {
id: 400293,
activity_identifier: '88392',
status: 'Complete'
}, {
id: 400402,
activity_identifier: '88547',
status: 'Complete'
}
];
return new Pretender(function() {
this.get('api/v1/users/:id', function(request) {
var user = users.find(function(user) {
if (user.id === parseInt(request.params.id, 10)) {
return user;
}
});
return [200, {"Content-Type": "application/json"}, JSON.stringify({user: user})];
});
this.get('api/v1/activities', function(request) {
return [200, {"Content-Type": "application/json"}, JSON.stringify({
activities: activities
})];
});
this.put('api/v1/users/:id', function(request) {
var response = Ember.$.parseJSON(request.requestBody);
response.user.id = parseInt(request.params.id, 10);
var oldUser = users.find(function(user) {
if (user.id === parseInt(request.params.id, 10)) {
return user;
}
});
var oldUserIndex = users.indexOf(oldUser);
if (oldUserIndex > -1) {
users.splice(oldUserIndex, 1);
users.push(response.user);
}
return [200, {"Content-Type": "application/json"}, JSON.stringify(response)];
});
});
}
When I run the tests, it fails because it reset the value to the one in the previous test. For example, when I run 'filter values can be cleared', the .filter-id input has the same .filter-id value from 'only saved filter can be edited. If I change the value in 'only saved filters can be edited'back to '', the 'filter values can be cleared' test passes.
Basically, the component sets the initialValues property when it first inserts the element. It's set to a copy of the filterValues property, so it should be set to the controller's filterValues property, and shouldn't change. However, it seems that the modified filterValues property is carried over to the next test, which means that initialValues is set to that modified property when it rerenders. So, the test rerenders the templates, but retains the modified values in the controller and component.
I can make the tests pass by creating an initialValues property in the controller and passing that into the component, but that'd mean having duplicate properties in the controller (since filterValues and initialValues would have the same values).
I could modify the user record in the component, but I thought we're supposed to only modify records in the controller or router. Besides, isn't the afterEach hook supposed to reset the app?
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
The code works every-time EXCEPT for when the router is first called with page load. The, the collection is created, but it's not populated with the notes.fetch();. I've been looking all over, and I can't see why this is happening.
For example, when I go to the URL to load this page, everything but what is in the collection loads. When I go to #blank/' and then go "Back" to thelist` view, the collection AND the models load as they are supposed to. SO how do I get the collection to load once the page loads?
Here's the code:
$(function() {
// Note: The model and collection are extended from TastypieModel and TastypieCollection
// to handle the parsing and URLs
window.Note = TastypieModel.extend({});
window.Notes = TastypieCollection.extend({
model: Note,
url: NOTES_API_URL
});
window.notes = new Notes();
window.NoteView = Backbone.View.extend({
className: "panel panel-default note",
template: _.template($('#notes-item').html()),
events: {
'click .note .edit': 'editNoteToggle',
'click .note .edit-note': 'doEdit'
},
initialize: function () {
_.bindAll(this, 'render');
this.model.bind('change', this.render);
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
editNoteToggle: function() {
console.log("I've toggled the edit box");
},
doEdit: function() {
console.log('This will edit the note');
}
});
window.NoteListView = Backbone.View.extend({
el: "#app",
template: _.template($('#notes-item-list').html()),
events: {
'click #add-note': 'addNote'
},
initialize: function () {
_.bindAll(this, 'render', 'addNote');
this.collection.bind('change', this.render);
},
render: function() {
this.$el.html(this.template());
console.log('before the loop');
console.log(this.collection.toJSON()); //<- Empty when it first loads, then contains the models when I visit another page and come "back" to this page
this.collection.each(function(note){
var view = new NoteView({ model: note });
$('#notes-list').append(view.render().el);
});
console.log('done');
$('#add-note-toggle').on('click', this, function() {
$('#note-add-form').toggle();
});
return this;
},
addNote: function() {
console.log('The add note was clicked');
}
});
window.NotesRouter = Backbone.Router.extend({
routes: {
'': 'list',
'blank/': 'blank'
},
initialize: function() {
// starts by assigning the collection to a variable so that it can load the collection
this.notesView = new NoteListView({
collection: notes
});
notes.fetch();
},
list: function () {
$('#app').empty();
$('#app').append(this.notesView.render().el);
},
blank: function() {
$('#app').empty();
$('#app').text('Another view');
}
});
window.notesRouter = new NotesRouter();
Backbone.history.start();
})
It looks like your listening to the wrong collection event. Try using
window.NoteListView = Backbone.View.extend({
// ...
initialize: function () {
this.collection.bind('reset', this.render);
}
// ...
});
window.NotesRouter = Backbone.Router.extend({
// ...
initialize: function() {
notes.fetch({reset: true});
}
// ...
});
Right now you are firing off an async collection.fetch(), which will eventually load the data. Problem is, once that data is loaded into the collection, it won't fire a change event, just a bunch of adds. When you go to the blank page and back, you're data has arrived by the second render call and displays properly.
If you modify your fetch() to throw a reset event and then listen for that, you'll have a freshly rendered NoteList once the data comes in without the need to go to the blank page.
I cannot fire observes function when was created object in Controller Array
My code:
Model
App.Meeting = Em.Object.extend({
id: null,
name: null,
type: null,
proposes: null
});
App.Meeting.reopen({
proposedChanged: function() {
//some do
}.observes('proposes')
});
Controller
App.meetingsController = Ember.ArrayController.create({
content: [],
loadList: function(){
var me = this;
$.getJSON(url,function(data){
if(data.status == 0){
$(data.meetings).each(function(index,value){
var m = App.Meeting.create(value)
me.pushObject(m);
});
}else{
alert('Error loading content');
}
});
},
});
App.meetingsController.loadList();
When i run application Controller has get JSON data and created App.Meeting with that data, but observer not fire
While I was creating a jsbin to play with #Darshan Sawardekar got it right, so now you have to answers to play with :)
The important code:
App.meetingsController = Ember.ArrayController.create({
content: [],
loadList: function(){
var me = this;
$.getJSON(url, function(data){
if(data.status == 0){
$(data.meetings).each(function(index, value){
var m = App.Meeting.create();
m.set('id', value.id);
m.set('name', value.name);
m.set('type', value.type);
m.set('proposes', value.proposes);
me.pushObject(m);
});
} else {
alert('Error loading content');
}
});
}
});
Hope it helps.
EDIT
See here for a working jsbin that shows the concept.
I think observers fire when you do meeting.set('proposes', 'value'). They don't fire inside a create call. You could modify your create to retouch proposes. This might work,
var m = App.Meeting.create(value);
m.set('proposes', value.proposes);
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.