I am stuck on the following issue:
I have a model with a property that defines if it is visibly selected or not, which I will call SelectModel for the purpose of this question.
SelectModel = Backbone.Model.extend({
defaults:{
isSelected: false
}
})
Now the first part that I do not really get is how I should handle the selection in general.
If I want to use the observer pattern, my View should listen to the change of the isSelected property. But my view also triggers this in the first place, so I would have.
SelectView = Backbone.View.extend({
initialize: function(){
this.model.bind("change:isSelected", this.toggleSelectionVisually)
},
events: {
"click" : toggleSelection
},
toggleSelection: function(){
this.model.set({"isSelected": !this.model.get("isSelected");
},
toggleSelectionVisually:(){
//some code that shows that the view is now selected
},
})
So this in itself already feels a bit absurd but I guess I just understand something wrong.
But the part which I really fail to implement without making my code horrible is handling the selection for multiple models that only one model is selected at a time.
SelectListView = Backbone.View.extend({
initialize: function(){
this.collection = new SelectList();
},
toggleSelection: function(){
????
}
})
So who should notify whom of the selection change? Which part should trigger it and which part should listen? I am really stuck on this one. For a single View it is doable, for a collection I am sadly lost.
I would have suggested the following simplification for your SelectView until I saw the second part of your question:
SelectView = Backbone.View.extend({
events: {
"click" : toggleSelection
},
toggleSelection: function(){
this.model.set({"isSelected": !this.model.get("isSelected");
//some code that shows whether the view is selected or not
}
});
However, since the isSelected attribute is apparently mutually exclusive, can be toggled off implicitly when another one is toggled on, I think the way you have it is best for your case.
So, using your existing SelectView and, you could have a SelectListView as follows. WARNING: it iterates over your entire collection of models each time one is selected. If you will have a large number of models this will not scale well, and you'll want to cache the previously-selected model rather than iterating over the entire collection.
SelectListView = Backbone.View.extend({
initialize: function(){
this.collection = new SelectList();
this.collection.bind('change:isSelected', this.toggleSelection, this);
},
toggleSelection: function(toggledModel){
//A model was toggled (on or off)
if(toggledModel.get('isSelected') {
//A model was toggled ON, so check if a different model is already selected
var otherSelectedModel = this.collection.find(function(model) {
return toggledModel !== model && model.get('isSelected');
});
if(otherSelectedModel != null) {
//Another model was selected, so toggle it to off
otherSelectedModel.set({'isSelected': false});
}
}
}
});
I would recommend that your model not keep track of this, but rather the view.
In my mind the model has nothing to do with its display, but rather the data that you're tracking. The view should encapsulate all the info about where and how the data is displayed to the user
So I would put isSelected as an attribute on the view. Then it's trivial to write a method to toggle visibility. If you then need to explain the other views that a specific view is selected you can attach a listener $(this.el).on('other_visible', toggle_show) which you can trigger on your toggle_visibility method with $(this.el).trigger('other_visible')
Very close to the solution suggested by #rrr but moving the logic from the View to the Collection where I think it bellows to:
SelectsCollection = Backbone.Collection.extend({
initialize: function() {
this.on( "change:selected", this.changeSelected );
},
changeSelected: function( model, val, opts ){
if( val ){
this.each( function( e ){
if( e != model && e.get( "selected" ) ) e.set( "selected", false );
});
};
},
});
There are different ways you could do it. You could trigger an event on the collection itself and have all the SelectModel instances listen for it and update themselves accordingly. That seems a bit wasteful if you have a lot of SelectModel instances in the collection because most of them won't end up doing any work. What I would probably do is keep track of the last SelectModel in your View:
SelectListView = Backbone.View.extend({
initialize: function(){
this.collection = new SelectList();
this.lastSelectedModel = null;
},
toggleSelection: function(){
// populate newSelectedModel with the SelectedModel that you're toggling
var newSelectedModel = getNewSelectedModel();
if (!newSelectedModel.get('isSelected')) {
// if the SelectModel isn't already selected, we're about to toggle it On
// so we need to notify the previously selected SelectModel
if (this.lastSelectedModel) {
this.lastSelectedModel.set({isSelected: false});
}
this.lastSelectedModel = newSelectedModel;
} else {
// if the newSelectedModel we're about to toggle WAS already selected that means
// nothing is selected now so clear out the lastSelectedModel
this.lastSelectedModel = null;
}
newSelectedModel.set({isSelected: !newSelectedModel.get('isSelected')});
}
})
Related
I have a simple backbone view as follows:
/**
* Renders a form view for an event object.
*/
APP.EventFormView = Backbone.View.extend({
tagName: 'form',
events: {
'keydown': 'keyPressed',
'focus input': 'inputChanged',
'change select': 'selectChanged',
'change textarea': 'textareaChanged'
},
initialize: function() {
this.template = _.template($('#newevent-form').html());
this.listenTo(this.model, 'change', this.render);
this.listenTo(APP.eventTypes, 'update', this.render);
this.listenTo(APP.selectedEvent, 'update', this.render);
},
render: function() {
var modelJSON = this.model.toJSON();
if ('id' in modelJSON && modelJSON.id !== "") {
this.loadForm();
} else if (!('id' in modelJSON) || modelJSON.id === "") {
this.loadForm();
} else {
this.$el.html('');
}
return this;
},
loadForm: function() {
var templateData = $.extend(this.model.toJSON(),
{"event_types":APP.eventTypes.toJSON()});
this.$el.html('');
this.$el.html(this.template($.extend(this.model.toJSON(),
{event_types: APP.eventTypes.toJSON()})));
$('.ev-main-container').html('').html(this.el);
},
inputChanged: function(e) {
console.log('inputChanged');
},
selectChanged: function(e) {
console.log('selectChanged');
},
textareaChanged: function(e) {
console.log('textareaChanged');
},
keyPressed: function(e) {
console.log('key pressed');
}
});
I initialize this view as follows under document.ready:
// Initialize the form view
APP.selectedEvent = APP.selectedEvent || new APP.Event();
APP.eventFormView = new APP.EventFormView({model: APP.selectedEvent});
APP.eventFormView.render();
But none of the events I have defined are firing for some reason, What is it that I am doing wrong here ?
Update:
Ok, I fugred out if i remove $('.ev-main-container').html('').html(this.el); from the loadForm method and instead intialize the view as follows, it works:
APP.eventFormView = new APP.EventFormView({
model: APP.selectedEvent,
el: $('.ev-main-container'),
});
I was able to resolve it but I still don't understand why this happens, could anyone throw a little light on what's going on and how this works.
jQuery's html function has a side effect that many people seem to forget about, from the fine manual:
jQuery removes other constructs such as data and event handlers from child elements before replacing those elements with the new content.
Consider what that means when you do something like this:
container.html(view.el);
container.html(view.el);
Everything will be fine after the first container.html() call. But the second will "remove ... event handlers from child elements" (such as view.el) before adding the new content. So after the second container.html() call, all the events on view.el are gone. Sound familiar?
You have lots of things that will call render on your view and render will eventually do this:
$('.ev-main-container').html('').html(this.el);
Your events will silently disappear the second time that gets called but the HTML will look just fine.
Consider this simplified example (http://jsfiddle.net/ambiguous/otnyv93e/):
var V = Backbone.View.extend({
tagName: 'form',
events: {
'click button': 'clicked'
},
initialize: function() {
this.template = _.template($('#t').html());
},
render: function() {
this.$el.html('');
this.$el.html(this.template());
$('.ev-main-container').html('').html(this.el);
return this;
},
clicked: function() {
console.log('clicked');
}
});
var v = new V;
v.render();
$('#re-render').click(function() {
v.render();
console.log('Re-rendered');
});
and you'll see exactly your problem.
If you make the view's el the .ev-main-container then you'll be using html() to alter the contents of el rather than altering the contents of the element that contains el. Once you're working entirely inside the el you're no longer accidentally re-using an element and no longer accidentally removing the event bindings from that element.
My rules of thumb for preventing event problems with Backbone:
Never attach views to existing DOM nodes, always let views create and own their own el and let the caller put that el in a container.
Call remove on views to dispose of them when they're no longer needed.
Don't try to re-use views, create them when you need them and remove them when you don't need them.
No view references anything outside its el.
There are exceptions (of course) and this approach won't solve everything but it is a good starting point and avoids most of the common problems.
I'm writing Todo app with Backbone.js
You can see part of my code below.
Model:
var Todo = Backbone.Model.extend({
defaults : {
title: 'Task Title',
complete: false
},
initialize: function(){
this.on("change:complete", function () {
alert("foo");
});
}
});
View:
var AppView = Backbone.View.extend({
collection: todoCollection,
el: 'body',
events: {
'click #tasks li .complete-task' : 'toggleComplete'
}
toggleComplete: function (e) {
var modelCid = $(e.target).parent('li').attr('id');
if ( this.collection.get(modelCid)['complete'] ){
this.collection.get(modelCid)['complete'] = false;
} else {
this.collection.get(modelCid)['complete'] = true;
};
}
});
But something working wrong and change event in the model doesn't working. I can't understand where I have mistakes.
Help me, please.
10q.
As per the Backbone Documentation:
Set model.set(attributes, [options])
Set a hash of attributes (one or
many) on the model. If any of the attributes change the model's state,
a "change" event will be triggered on the model. Change events for
specific attributes are also triggered, and you can bind to those as
well, for example: change:title, and change:content. You may also pass
individual keys and values.
So you need to be using the set method on the model for these events to be fired. So you would need to use something like this:
this.collection.get(modelCid).set('complete',false);
I have a sortable accordion loaded with a foreach-template loop over a ko.observableArray() named "Tasks".
In the accordion I render the TaskId, the TaskName, and a task Description - all ko.observable().
TaskName and Description is rendered in input/textarea elements.
Whenever TaskName or Description is changed, an item is de-selected, or another item is clicked on, I want to call a function saveEdit(item) to send the updated TaskName and Description to the database via an ajax request.
I need to match the TaskId with the Tasks-array to fetch the actual key/value-pair to send to the saveEdit().
This is the HTML:
<div id="accordion" data-bind="jqAccordion:{},template: {name: 'task-template',foreach: Tasks,afteradd: function(elem){$(elem).trigger('valueChanged');}}"></div>
<script type="text/html" id="task-template">
<div data-bind="attr: {'id': 'Task' + TaskId}" class="group">
<h3><b><span data-bind="text: TaskId"></span>: <input name="TaskName" data-bind="value: TaskName /></b></h3>
<p>
<label for="Description" >Description:</label><textarea name="Description" data-bind="value: Description"></textarea>
</p>
</div>
</script>
This is the binding:
ko.bindingHandlers.jqAccordion = {
init: function(element, valueAccessor) {
var options = valueAccessor();
$(element).accordion(options);
$(element).bind("valueChanged",function(){
ko.bindingHandlers.jqAccordion.update(element,valueAccessor);
});
},
update: function(element,valueAccessor) {
var options = valueAccessor();
$(element).accordion('destroy').accordion(
{
// options put here....
header: "> div > h3"
, collapsible: true
, active: false
, heightStyle: "content"
})
.sortable({
axis: "y",
handle: "h3",
stop: function (event, ui) {
var items = [];
ui.item.siblings().andSelf().each(function () {
//compare data('index') and the real index
if ($(this).data('index') != $(this).index()) {
items.push(this.id);
}
});
// IE doesn't register the blur when sorting
// so trigger focusout handlers to remove .ui-state-focus
ui.item.children("h3").triggerHandler("focusout");
if (items.length) $("#sekvens3").text(items.join(','));
ui.item.parent().trigger('stop');
}
})
.on('stop', function () {
$(this).siblings().andSelf().each(function (i) {
$(this).data('index', i);
});
})
.trigger('stop');
};
};
My first thought was to place the line
$root.SelectedTask( ui.options.active );
in an .on('click') event function where SelectedTask is a ko.observable defined in my viewModel. However, the .on('click') event seems to be called a lot and it's generating a lot of traffic. Also, I can´t quite figure out where to put the save(item) call that sends the selected "item" from Tasks via an ajax-function to the database.
Any help is highly appreciated. Thanks in advance! :)
Whenever TaskName or Description is changed, an item is de-selected, or another item is clicked on, I want to call a function saveEdit(item) to send the updated TaskName and Description to the database via an ajax request.
This sounds like the core of what you want to do. Let's start out with a Task model
function Task (data) {
var self = this;
data = data || {};
self.id = ko.observable(data.id);
self.name = ko.observable(data.name);
self.description = ko.observable(data.description);
}
And then we need our View Model:
function ViewModel () {
var self = this;
self.tasks = ko.observableArray();
self.selectedTask = ko.observable();
self.saveTask = function (task) {
$.ajax({ ... });// ajax call that sends the changed data to the server
};
var taskSubscription = function (newValue) {
self.saveTask(self.selectedTask());
};
var nameSubscription, descriptionSubscription;
self.selectedTask.subscribe(function (newlySelectedTask) {
if (newlySelectedTask instanceof Task) {
nameSubscription =
newlySelectedTask.name.subscribe(taskSubscription);
descriptionSubscription =
newlySelectedTask.description.subscribe(taskSubscription);
self.saveTask(newlySelectedTask);// But why?
}
});
self.selectedTask.subscribe(function (currentlySelectedTask) {
if (currentlySelectedTask instanceof Task) {
nameSubscription.dispose();
descriptionSubscription.dispose();
self.saveTask(currentlySelectedTask);// But why?
}
}, null, 'beforeChange');
}
So what's going on here? Most of this should be pretty self explanatory so I'm just going to focus on the subscriptions. We created a taskSubscription function so we're not constantly having it defined every time the self.selectedTask changes.
We have two subscriber functions. The first fires after the selectedTask's value has changed and the second fires before it changes. In both, we verify that the new value is an instance of a Task object. In the after change subscription, we set up two subscriptions on the name and description properties. Then I capture the return value from the subscription function into two private variables. These are used in the before change function to dispose of those subscriptions so that if those Tasks are ever updated when they're not currently selected, then we don't continue to fire off the saveTask function.
I've also added self.saveTask in each of the subscriptions to the selectedTask observable. I asked why in here because, why save it if we don't know if the value has changed or not? You may be making ajax requests needlessly here.
Also, as demonstrated by this code, you can set up these subscriptions to make ajax requests every time the value changes but that may end up making a LOT of requests. A better option might be to set up functionality in your Task model that can track whether or not it is 'dirty' or not. Meaning one or more of its values have changed that requires updating.
function Task (data) {
var self = this;
// Make a copy of the data object coming in and use this to save previous values
self._data = data = $.extend(true, { id: null, name: null, description: null }, data);
self.id = ko.observable(data.id);
self.name = ko.observable(data.name);
self.description = ko.observable(data.description);
for (var prop in data) {
if (ko.isSubscribable(self[prop])) {
self[prop].subscribe(function (oldValue) {
data[prop] = oldValue;
}, null, 'beforeChange');
}
}
}
Task.prototype.isDirty = function () {
var self = this;
for (var prop in self._data) {
if (ko.isSubscribable(self[prop])) {
if (self._data[prop] !== self[prop]())
return true;
}
}
return false;
};
And of course you need a way to save it, or make it not dirty
Task.prototype.save = function () {
var self = this;
for (var prop in self._data) {
if (ko.isSubscribable(self[prop])) {
self._data[prop] = self[prop]();
}
}
};
Using the same concept you can also create Task.prototype.revert that does the opposite of what .save does. With all this in place, you could forego setting up the subscriptions on the individual name and description properties. I wanted to show that option to just demonstrate how one might want to use the .dispose method on a subscription. But now you can just subscribe to the selectedTask observable ('beforeChange') and see if the currently selected task that you're about to swap out isDirty. If it is, call the saveTask function, and when that completes, call the .save function on the Task so that it is no longer dirty.
This is probably the route I would go in implementing something like this. The beauty of it is, I haven't written a single line of code that has anything to do with the manipulating the View. You can set the selectedTask any way you see fit. What I would do is, bind the selectedTask observable to a click binding on the <h3> element inside of the accordion. That way, every time a user clicks on any of the accordions, it will potentially save the previously selected task (if any of the property values had changed).
Hopefully that addresses your scenario here of trying to save a Task when certain events are triggered.
I just don't have idea what causes problem and need help. Before posting I've came up to alternative solution, but I want to learn why this is not working properly.
I have router that initialize view which initialize entity collection and views like so:
advertiser_manage_campaign: function () {
this.campaignListView = new window.CampaignListView;
this.mainSidebar = new window.MainSidebar;
},
CampaignListView:
window.CampaignListView = Backbone.View.extend({
el: ("#right_column"),
initialize: function () {
this.render();
this.campaignCollection = new Campaign.CampaignCollection;
this.campaignCollectionView = new Campaign.CampaignCollectionView({ model: this.campaignCollection });
this.campaignCollection.fetch();
},
events: {
"click .campaign_dialog": "openCampaignDialog"
},
openCampaignDialog: function (e) {
var that = this;
var itemID = $(e.target).attr("item-id");
var model = {}; //model to populate dialog inputs
if (!isNaN(itemID))
model = this.campaignCollection.get(itemID).toJSON(); //get existing model from collection <- after described procedure, error
Campaign.Dialog.open(model, function (data) {
if (isNaN(itemID)) {//model does not exist, create
that.campaignCollection.create(data, { wait: true,
error: function (model, error) {
dialoger.showErrors(JSON.parse(error.responseText).errors);
},
success: function (mdl, response) { window.Campaign.Dialog.close(); }
});
} else {//model exist, update
model = that.campaignCollection.get(itemID);
model.save(data, { wait: true,
error: function (mdl, error) {
dialoger.showErrors(JSON.parse(error.responseText).errors);
},
success: function (mdl, response) { window.Campaign.Dialog.close(); }
});
}
});
return false;
},
render: function () {
$(this.el).html(window.Templates.getHTML("campaign_list_view", {}));
$(".button", $(this.el)).button();
}
});
-
openCampaignDialog
is for both edit models and creating new. Every view(table row) of model
has button with class ".campaign_dialog" and there is button for adding new model with same class.
Campaign.Dialog.open
shows dialog populated with model and in callback returns JSON from dialog form.
If I create new model via dialog, I can edit it right away, but when I create new model, change view, back to this view, create again new model, change view and then again back, click edit on last added item, I get error on commented line as model with this ID is not in collection, although it is. Response from server is OK. Obviously, I'm doing something wrong and after one day, I don't see what it is.
Alternative solution I've came up to is to create and populate dialog from event of model view (this works), but I thought that CampaingCollectionView or CampaingView should not deal with adding or editing models so I've implemented this in 'higher' view.
Thanks everyone for helping me...
Edit:
var CampaignCollectionView = Backbone.View.extend({
el: (".content_table tbody"),
initialize: function () {
this.model.bind("reset", this.render, this);
this.model.bind("add", this.add, this);
},
render: function () {
$(this.el).empty();
_.each(this.model.models, function (campaign) {
$(this.el).append(new CampaignView({ model: campaign }).render().el);
}, this);
return this;
},
add: function (model) {
window.Appender.AppendAndScroll($(new CampaignView({ model: model }).render().el), this.el);
}
});
I've found solution.
Problems arise, though, when we bind objects together through these
events but we don’t bother unbinding them. As long as these objects
are bound together, and there is a reference in our app code to at
least one of them, they won’t be cleaned up or garbage collected. The
resulting memory leaks are like the zombies of the movies – hiding in
dark corners, waiting to jump out and eat us for lunch.
Source: http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/
Author suggests unbinding mechanism, but I'm going to reuse same objects if exist.
Router:
advertiser_manage_campaign: function () {
if (!this.campaignListView)
this.campaignListView = new window.CampaignListView;
else
this.campaignListView.initialize();
this.mainSidebar = new window.MainSidebar;
},
If someone thinks this is not best solution, I would like to hear why.
Thank you all who tried to help!
I have a collection of flash cards that are tied to a Backbone collection. Once I get the collection, I create an instance of a player model.
Then the user can navigate through the rest of the flash cards using the "next" and "previous" buttons. My first stab in doing this which I thought was simple was to pass the flashCards to a player like this.
Unfortunately, this design is causing the next and previous button events to be bound every time they are clicked. So, after the first time clicking on the next button for example, the event starts firing more than once. I read somewhere about ghost views, but could not exactly figure out how I can break the code below into a chunk that will help me prevent the ghost view issue.
var flashCards = new Quiz.Collections.FlashCards({
id: this.model.get('card_set_id')
});
Quiz.player = new Quiz.Models.FlashCardPlayer({
collection: flashCards
})
Quiz.Models.FlashCardPlayer = Backbone.Model.extend({
defaults: {
'currentCardIndex': 0
},
initialize: function(){
this.collection = this.get('collection');
this.showCard();
},
showCard: function(){
var flashCard = this.collection.at(this.get('currentCardIndex'));
var cardView = new Quiz.Views.FlashCardPlayer({
model: flashCard
});
},
currentFlashCard: function(){
return this.get('currentCardIndex');
},
previousFlashCard: function(){
var currentFlashCardIndex = parseInt(this.get('currentCardIndex'), 10);
if(currentFlashCardIndex <= 0){
console.log("no less");
}
this.set({
'currentCardIndex': currentFlashCardIndex--
});
this.showCard();
},
nextFlashCard: function(){
var currentFlashCardIndex = parseInt(this.get('currentCardIndex'), 10);
if(currentFlashCardIndex >= this.collection.length){
console.log("no more");
}
currentFlashCardIndex = currentFlashCardIndex + 1;
this.set({
'currentCardIndex': currentFlashCardIndex
});
console.log(this.get('currentCardIndex'));
this.showCard();
}
});
Quiz.Views.FlashCardPlayer = Backbone.View.extend({
el: $('#cardSet'),
tagName: 'div',
_template: _.template($('#playerTemplate').html()),
initialize: function(){
console.log("in view flashcardplayer", this);
this.render();
},
events: {
'click #previous': 'getPreviousCard',
'click #next': 'getNextCard'
},
render: function(){
$(this.el).html(this._template(this.model.toJSON()));
return this;
},
getPreviousCard: function(){
this.close();
Quiz.player.previousFlashCard();
},
getNextCard: function(){
this.close();
Quiz.player.nextFlashCard();
}
});
script#playerTemplate(type="text/template")
<div id="state"></div>
<div id="previous">Previous</div>
<div id="card">
<h2><%= question %></h2>
<h3><%= answer %></h3>
</div>
<div id="next">Next</div>
You're creating a new instance of Quiz.Views.FlashCardPlayer each time you show a new card. Each of these instances does its own event handling, so each instance is binding to the same #next and #previous elements.
I think there are a couple of conceptual issues here:
You only need one FlashCardPlayer view, which should bind events on the next/previous elements. You probably ought to have a separate FlashCard view, which displays a single card, and the player can swap those views in and out as the next/previous buttons are pressed. As a general rule, if you have an element with an id, you should only be rendering and binding to it once, with a single view instance, otherwise you end up with the same issue you have now.
You're trying to stuff way too much into the FlashCardPlayer model. As a rule, models should only know about their data, not about the views used to display them (in part because one model might need to be displayed in a variety of views). I don't mind having the nextFlashCard() and previousFlashCard() methods on the model, as this is still in the realm of storing data about the collection, but the showCard() method is really moving squarely into view territory, as it deals with presentation logic. A much better idea would be to have your view bind to the change:currentCardIndex event on the model and handle the display of the new card, using this.model.get('currentCardIndex')) (or a new getCurrentCard() method) to get it.