Trigger function when user changes input value (backbone.js) - javascript

I just started with backbone.js and is currently making a page which has a div #listing_filter containing text input elements and a table showing some listings fetched from a RESTful backend (PHP/Codeigniter). The values in the text input will act as filters to narrow down the results retrieved by the server.
Problem: Whenever the value in any of the text boxes changes, I want the browser to GET another set of results based on the filter values. Below is my attempt, where the updateFilter function does not fire even though the text input value was changed. Any ideas what went wrong?
Another question will be whether I should put the contents of #listing_filter into a template, or just hardcode it into the main body HTML? Thanks!
JS Code
window.ListingFilterView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'updateFilter');
},
events: {
'change input' : 'updateFilter'
},
updateFilter: function() {
console.log('hey');
}
});
// Router
var AppRouter = Backbone.Router.extend({
routes: {
'': 'listings',
},
listings: function() {
//... some other code here
this.listingFilterView = new ListingFilterView();
}
});
HTML Code
<div id="listing_filter">
Price: <input type="text" id="listing_filter_price" />
Beds: <input type="text" id="listing_filter_bedroom" />
Baths: <input type="text" id="listing_filter_bathroom" />
</div>

A Backbone view will only respond to events on the view's el or on elements that are inside its el. By default, the view's el is just an empty <div> and you're not telling the view to use anything else.
You can tell the view which el to use (http://jsfiddle.net/ambiguous/5yXcU/1/):
new ListingFilterView({ el: $('#listing_filter') })
// Or like this:
new ListingFilterView({ el: '#listing_filter' })
or you can let the view attach itself to that element using setElement (http://jsfiddle.net/ambiguous/APEfa/1/):
initialize: function() {
this.setElement($('#listing_filter'));
// or setElement('#listing_filter')
}
or set the el when you define the view (http://jsfiddle.net/ambiguous/nyTZU/):
window.ListingFilterView = Backbone.View.extend({
el: '#listing_filter',
//...
});
Once that's out of the way, you'll need to understand that an <input> won't trigger a change event until it loses focus so you'll have to wait for the user to tab-out of the input or switch to listening for keypress events and using a timer to detect when they've stopped typing.

Related

Backbone Views UI

I am wondering if there is a better way of doing this.
I have some HTML that needs some events attaching to it.
Question 1:
There is no data, models or collections behind it so I assume no need for a render method?
Question 2:
I am assuming it should be a view in backbone because it is a single piece of UI that needs code attaching to it?
Basically what I have is a panel with show and hide functionality, which shows some check boxes for saving settings. When the panel closes it will save the states of the check boxes.
Here is the HTML:
<div id="panel-holder">
<div id="settings">
<ul class="settingsChecks">
<li>
<label>Display Desktop Notification Popup </label>
<input type="checkbox" id="formDisplayPopup" checked="checked"/>
</li>
<li>
<label>Play Alert Sound </label>
<input type="checkbox" id="formPlaySounds" checked="checked"/>
</li>
</ul>
</div>
</div>
So the above code is attached to a view using #panel-holder.
Here is the Backbone code:
var SettingsView = Backbone.View.extend({
el: '#panel-holder',
events: {
'click #click': 'toggleContent'
},
initialize: function() {
this.toggleContent();
},
showmeState: true,
toggleContent: function(){
if (this.showmeState === false) {
this.openPanel();
} else {
this.closePanel();
}
},
closePanel: function() {
this.$el.find('#settings').slideUp('fast');//Close Panel
this.$el.find('#click').text("Open Settings");//Change Text
this.showmeState = false;
this.saveSettings();
},
openPanel: function() {
this.$el.find('#settings').slideDown('fast');//Open Panel
this.$el.find('#click').text("Close Settings");//Change Text
this.showmeState = true;
},
saveSettings: function() {
//when the panel closes get the states of the checkboxes and save them
}
});
Question 3:
Should I be using jQuery .find('') in the open and close panel areas? Is there a better way of attaching functionality to these elements.
Question 4:
Is this code and my understanding of Backbone Views ok? Am I way off course?
Answers
I would include a render method that returns itself so that you can append the view to the #panel-holder element
Yes, this is fine
Always use $.find("") when working within a view's elements. Just index the elements so you can access them as this.$settings, etc
No looks good generally
Code
Here is my recommended code in Coffeescript (sorry I'm lazy):
Also uses Handlebars library to compile templates
tmpl = ....all your html...
SettingsView = Backbone.View.extend
attributes:
id: 'settings'
template: Handlebars.compile tmpl
events:
'click #click': 'toggleContent'
initialize:
#toggleContent()
showMeState: true
toggleContent: ->
#showMeState is false then #openPanel()
else #closePanel()
closePanel:->
#$settings.slideUp('fast')
#$click.text('Open Settings')
#showMeState = false
#saveSettings()
openPanel: ->
#$settings.slideDown('fast')
#$click.text('Close Settings')
#showMeState = true
saveSettings: ->
render: ->
#$el.append #template
#Store settings and click
#$settings = #$el.find('#settings')
#$click = #$el.find('#click')
#
settings = new SettingsView
$('#panel-holder').append settings.render().el
Question 1: There is no data, models or collections behind it so I
assume no need for a render method?
For now it is not required. But if you want to add extra functionality or if the UI changes in any way later then you might be requiring one.
Question 2: I am assuming it should be a view in backbone because it
is a single piece of UI that needs code attaching to it?
Yes. it is a view.
Question 3: Should I be using jQuery .find('') in the open and close
panel areas? Is there a better way of attaching functionality to these
elements.
this.$el.find('#settings') is perfectly fine.
You can also use either $('#settings', this.$el) or this.$('#settings')
But remember that you are using ID selectors . And ID will be unique on the page. So you do not need to find it in the context of the view
$('#setting') should be good enough
Question 4: Is this code and my understanding of Backbone Views ok? Am
I way off course?
You are doing perfectly well. But the thing is in backbone you can get a task done in many ways which works. And you need to choose the best approach amongst them. You will get to know the more you work with it. So do not worry about it.
The same can be condensed into a single method that will take care of toggling
var SettingModel = Backbone.Model.extend({
defaults: {
showmeState : false
}
});
var settingModel = new SettingModel();
var SettingsView = Backbone.View.extend({
el: '#panel-holder',
events: {
'click #click': 'toggleState'
},
initialize: function () {
// Listen to the Model that triggers
this.listenTo(settingModel, 'change', this.toggleContent);
this.model.trigger('change');
},
toggleState: function() {
//When Clicked just negate the boolean so that it triggers the change event
this.model.set('showmeState', !this.model.get('showmeState'));
},
toggleContent: function() {
var check = !this.model.get('showmeState'),
txt = check === true ? "Close Settings" : "Open Settings";
$('#click').text(txt);
check === true ? $('#settings').slideUp('fast')
: $('#settings').slideDown('fast');
if(check)
saveSettings();
},
saveSettings: function () {
//when the panel closes get the states of the checkboxes and save them
}
});
If you think check for condition is an overkill, then a simple if should be sufficient.

backbone and $el element

I'm trying to develop my first backbone application. All seems ok, but when i render the view and append some html to the $el, nothing is rendered in the page.
Rest service calls done ok, the Backbone.Router.extend is declared inside $(document).ready(function () {}); to ensure that the DOM is created.
Debugging my javascript, the el element get to contain the correct value in the innerHTML property, but when the whole page is rendered, this value doesn't appear in the page.
¿What am i doing wrong?
My View code:
window.ProductsListView = Backbone.View.extend({
id: 'tblProducts',
tagName: 'div',
initialize: function (options) {
this.model.on('reset', this.render, this);
},
render: function () {
// save a reference to the view object
var self = this;
// instantiate and render children
this.model.each(function (item) {
var itemView = new ProductListItemView({ model: item });
var elValue = itemView.render().el;
self.$el.append(elValue); // Here: the $el innerHTML is ok, but in the page it disappear. The id of element is div#tblProducts, so the element seems correct
});
return this;
}
});
window.ProductListItemView = Backbone.View.extend({
tagName: 'div',
template: _.template(
'<%= title %>'
),
initialize: function (options) {
this.model.on('change', this.render, this);
this.model.on('reset', this.render, this);
this.model.on('destroy', this.close, this);
},
render: function () {
$(this.el).html(this.template(this.model.toJSON()));
// $(this.el).html('aaaaaa'); // This neither works: it's not a template problem
return this;
},
close: function () {
$(this.el).unbind();
$(this.el).remove();
}
});
Here i load products (inside Backbone.Router.extend). This is executed correctly:
this.productsList = new ProductsCollection();
this.productsListView = new ProductsListView({ model: this.productsList });
this.productsList.fetch();
And this is the html element i want to render:
<div id="tblProducts">
</div>
Thanks in advance,
From the code you have posted, you are not actually inserting your ProductsListView in to the DOM or attaching it to an existing DOM element.
The way I like to look at it is you have two types of Views:
Those that are dynamically generated based on data returned from the server
Those that already exist on the page
Usually in the case of lists, the list already exists on the page and it's items are dynamically added. I have taken your code and restructured it slightly in this jsfiddle. You will see that the ProductListView is binding to an existing ul, and ProductItemView's are dynamically appended when they are added to the Collection.
Updated jsfiddle to demonstrate Collection.reset
The el property exists within the view if it is rendered or not. You can't say it is ok there because Backbone will create an element if no element is passed (empty div).
If you want to render the view you should determine what is the container of the element? Do you have an html you want to attach the view to?
Try passing a container element by calling the view with an el like
this.productsListView = new ProductsListView({ model: this.productsList, el : $("#container") });
Of course you can create the view and attach it to the DOM later:
el: $("#someElementID") //grab an existing element
el.append(view.render().el);
Your view wont exist in the dom until you attach it somewhere.

Is correct replace content in the same place without remove the previous content model using Backbone.js?

I have a web application developed with Backbone.js. In the application, there are some buttons that remove the content view, but not the content model when pushed. For example, If I push the same button multiple times, the content is replaced, but the model of that content isn't removed.
How can I remove it?
I know how to remove the content with other different button, but I don't know how to remove the content if the same button (or other button not destined to delete but to add) is pushed.
The example code:
HTML:
<button class="ShowCam"></button>
<button class="camClose"></button>
<button class="anotherButton"></button>
JS:
var camContent = Backbone.View.extend({
el: "body",
events: {
"click .ShowCam": "addContentCam",
"click .anotherButton": "otherAddContentFunction"
},
initialize: function() {
_.bindAll(this);
this.model = new ContentCollection();
this.model.on("add", this.contentAdded);
this.model.on("remove", this.removeContentCam);
},
addContentCam: function(event) {
this.model.add({ modelName: "IPcam"});
contentAdded: function(content) {
if (content.view == null) {
var templ_name = 'cam';
content.view = new ContentView({
model: content,
template: $.trim($("[data-template='"+ templ_name +"'] div").html() || "Template not found!")});
$("div.camBox").empty();
this.$el.find(".content").find("div.camBox").append(content.view.render().el);
}
},
removeContentCam: function(content) {
if (content.view != null) {
content.view.remove();
}
content.clear(); //Clear the properties of the model
}
});
var ContentView = Backbone.View.extend({
tagName: "div",
template: null,
events: {
"click .camClose": "removeView"
},
initialize: function() {
_.bindAll(this);
this.template = this.options.template;
},
render: function() {
this.$el.html(Mustache.render(this.template, this.model.toJSON()));
return this;
},
removeView: function() {
this.model.collection.remove(this.model); //Remove the model of the collection
}
});
Javascript uses a garbage collection system to do its memory management. What this means is that you can delete anything simply by removing all references to it (well, technically it doesn't actually get deleted until the garbage collector gets to it, but essentially it's deleted).
So, if you want to make sure that a model gets removed, you don't need to call any special methods, you just need to do delete someView.model on every view (or other place in your code) that references that model.
You can actually see all this in practice if you look at the remove method on Backbone.View. You'll find that all it really does (besides triggering events) is call an internal method _removeReference. And what does _removeReference do? This:
if (this == model.collection) {
delete model.collection;
}
// (there's also an event-related line here)
Now, all that being said, if you're making a new view to replace an old one, and they both have the same model ... well you likely shouldn't be making a new view in the first place. The more standard Backbone way of handling such situations is to just re-call render on the view (instead of making a new one).

View Events not firing on created elements?

Trying to create a todo example app to mess around with backbone. I cannot figure out why the click event for the checkbox of a task is not firing. Here is my code for the TaskCollection, TaskView, and TaskListView:
$(document).ready(function() {
Task = Backbone.Model.extend({});
TaskCollection = Backbone.Collection.extend({
model: 'Task'
});
TaskView = Backbone.View.extend({
tagName: "li",
className: "task",
template: $("#task-template").html(),
initialize: function(options) {
if(options.model) {
this.model = options.model
}
this.model.bind('change',this.render,this);
this.render();
},
events: {
"click .task-complete" : "toggleComplete"
},
render: function(){
model_data = this.model.toJSON();
return $(_.template(this.template, model_data));
},
toggleComplete: function() {
//not calling this function
console.log("toggling task completeness");
}
});
TaskListView = Backbone.View.extend({
el: $("#task-list"),
task_views: [],
initialize: function(options) {
task_collection.bind('add',this.addTask,this);
},
addTask: function(task){
task_li = new TaskView({'model' : task});
this.el.append(task_li.render());
this.task_views.push(task_li);
},
});
});
Template for the task:
<script type='text/template' id='task-template'>
<li class="task">
<input type='checkbox' title='mark complete' class='task-check' />
<span class='task-name'><%= name %></span>
</li>
</script>
I can't seem to figure out why the toggleComplete event will not fire for the tasks. how can I fix this?
The problem here is that the backbone events only set to the element of the view (this.el) when you create a new view. But in your case the element isn't used. So you have the tagName:li attribute in your view, which let backbone create a new li element, but you doesn't use it. All you return is a new list element created from your template but not the element backbone is creating, which you can access by this.el
So you have to add your events manually to your element created by your template using jQuery or add your template as innerHtml to your element:
(this.el.html($(_.template(this.template, model_data)))
Try changing the lines where you set your listeners using .bind() to use .live(). The important difference is .live() should be used when you want to bind listeners to elements that will be created after page load.
The newest version of jQuery does away with this bit of ugliness and simplifies the methods used to set event listeners.
Your event is binding to a class of .task-complete but the class on your checkbox is .task-check
Try modifying your render function to call delegateEvents() like so:
render: function(){
model_data = this.model.toJSON();
this.el = $(_.template(this.template, model_data));
this.delegateEvents();
return this.el;
},
You'd really be better off changing your template to not include the li and then return this.el instead of replacing it, but if you want the events to work you need to have this.el be the root element one way or another; delegateEvents() re-attaches the event stuff, so when you change this.el that should fix the issue.
#Andreas Köberle answers it correctly. You need to assign something to this.elto make events work.
I changed your template and your TaskView#render() function.
This JSFiddle has the changes applied.
New render function:
render: function(){
var model_data = this.model.toJSON();
var rendered_data = _.template(this.template, model_data);
$(this.el).html(rendered_data);
return this;
}
It is recommended that the render() returns this.
One line in your TaskListView#addTask function changes from this.el.append(task_li.render()); to this.el.append(task_li.render().el);.
Template change
Since we are using this.el in the render() function, we have to remove the <li> tag from the template.
<script type='text/template' id='task-template'>
<input type='checkbox' title='mark complete' class='task-complete' />
<span class='task-name'><%= name %></span>
</script>

backbone.js data linking

I'm trying to link an input, a model, and a dom element.
<div data-carName="Isetta">
<input type="textfield" name="speed"/>
<br />
<br />
Speed: <br />
<div>{speed}</div>
</div>
var Isetta = {
speed:speedval
}
What do I do if I want whenever the card speed input is changed, for the speed dom element to change with it, and the javascript object/model to change as well?
I can do this easily with jQuery data-linking. How do I do it with backbone.js?
Thanks.
You may also want to consider binding keystroke events and timers to the input field so that when a user has finished typing in their input, you trigger an event on the model that then updates the view:
If you add id=name to that field, then in your view you can add something like:
events: {
"keypress #speed" : "updateViewOnEnter"
},
updateViewOnEnter: function(e) {
if (e.keyCode != 13) return;
e.preventDefault();
this.model.trigger('speed:change');
},
Check out this throttle function from Remy Sharp if you want to throttle function calls as a user is still typing in that input field:
http://remysharp.com/2010/07/21/throttling-function-calls/
events: {
"keypress #speed" : "updateViewOnDelayedKeypress"
},
updateViewOnDelayedKeypress: function(e) {
throttle(function (e) {
this.model.trigger('speed:change');
}, 250));
},
var Car = Backbone.Model.extend({ });
var CarView = Backbone.View.extend({
model: Car,
initialize: function() {
this.model.bind('change', _.bind(this.render, this));
}
render: function() { ... }
}
The Car model will generate events, and CarView responds to them. The list of events is far broader-- and you can add your own, if you like-- than those of data-link. jQuery Data-Link appears to be concerned entirely with forms, and has a limited filtering mechanism. It's interesting, but it's clearly tackling a different problem from the one Backbone and other MVC libraries are intended to cover.
You can also check out this library: https://github.com/derickbailey/backbone.modelbinding which adds a module that will handle dynamic and convention based binding for you.

Categories